You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Swift枚举TrackingEvent中获取随机字符串值?

如何从Swift枚举中获取随机字符串值?

你这个TrackingEvent枚举是基于String类型的,要从中随机拿到对应的字符串值其实不难,核心思路是先获取枚举的所有case,再随机挑选一个取出它的rawValue就行。之前你在StackOverflow没找到合适方案,大概率是没用到CaseIterable这个关键协议,我给你具体实现步骤:

步骤1:让枚举遵循CaseIterable协议

这个协议能帮我们自动生成包含所有枚举case的数组allCases,直接给枚举加上这个协议就行:

enum TrackingEvent: String, CaseIterable {
    case notificationScreenLoaded = "Notification Screen"
    case homeScreenLoaded = "Home Screen"
    case homeScreenViewBill = "Home Screen View Bill Button"
    case homeScreenPayBill = "Home Screen Pay Bill Button"
    case homeScreenViewLastPayment = "Home Screen Last Payment Section"
    case chartToggleUsage = "Charts Toggle"
    case chartExplanation = "Charts Explanation Screen"
}

步骤2:实现随机获取字符串的逻辑

你可以给枚举加一个静态属性,封装随机获取的逻辑,这样用起来更方便:

extension TrackingEvent {
    static var randomRawValue: String? {
        allCases.randomElement()?.rawValue
    }
}

调用示例

现在你只需要一行代码就能拿到随机的字符串值了:

if let randomEventString = TrackingEvent.randomRawValue {
    print("随机选中的事件字符串:\(randomEventString)")
}

如果不想写扩展,也可以直接在需要的地方这么写,效果是一样的:

let randomString = TrackingEvent.allCases.randomElement()?.rawValue

这里randomElement()返回的是可选值,因为如果枚举没有任何case的话会返回nil,但你的枚举有多个case,所以实际使用时大概率能拿到有效值。

内容的提问来源于stack exchange,提问作者Moses Liao GZ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:55:30