如何获取随机枚举字符串?

时间:2018-03-20 08:04:25

标签: swift

enum TrackingEvent: String {
    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"
}

对于此示例,如何获取随机字符串?到目前为止,我在StackOverflow示例中搜索的枚举都是UInt32返回类型

2 个答案:

答案 0 :(得分:3)

将all放入数组并发出随机索引项

/**
 * Static helper that can be used to run a {@link SpringApplication} from the
 * specified source using default settings.
 * @param source the source to load
 * @param args the application arguments (usually passed from a Java main method)
 * @return the running {@link ApplicationContext}
 */
public static ConfigurableApplicationContext run(Object source, String... args) {
    return run(new Object[] { source }, args);
}

/**
 * Static helper that can be used to run a {@link SpringApplication} from the
 * specified sources using default settings and user supplied arguments.
 * @param sources the sources to load
 * @param args the application arguments (usually passed from a Java main method)
 * @return the running {@link ApplicationContext}
 */
public static ConfigurableApplicationContext run(Object[] sources, String[] args) {
    return new SpringApplication(sources).run(args);
}

答案 1 :(得分:2)

您需要创建一个函数来获取随机UInt32,其上限等于枚举TrackingEvent中的个案数,并根据随机数返回大小写。

enum TrackingEvent: String {
    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"

    static func random() -> TrackingEvent {
        let rand = arc4random_uniform(7)
        switch rand {
        case 1:
            return .homeScreenLoaded
        case 2:
            return .homeScreenViewBill
        case 3:
            return .homeScreenPayBill
        case 4:
            return .homeScreenViewLastPayment
        case 5:
            return .chartToggleUsage
        case 6:
            return .chartExplanation
        default:
            return .notificationScreenLoaded
        }
    }
}

你可以像使用它一样 let random = TrackingEvent.random()