swift – 从枚举的子部分中选择一个随机值

swift – 从枚举的子部分中选择一个随机值,第1张

概述给出一个 Swift枚举: enum PerformerPosition: Int { case String_Violin1 case String_Violin2 case String_Viola case String_Cello case String_CB case Wind_Oboe case Wind_Clarinet 给出一个 Swift枚举:

enum Performerposition: Int {    case String_Violin1    case String_Violin2    case String_Viola    case String_Cello    case String_CB    case Wind_Oboe    case Wind_Clarinet    case Wind_Flute    ...}

(对于项目的需要,我无法使用嵌套枚举.)我想只使用String_前缀随机选择一个枚举值.

到目前为止,我所知道的唯一方法是从所有可用的案例中执行随机枚举值,如下所示:

private static let _count: Performerposition.RawValue = {    // find the maximum enum value    var maxValue: Int = 0    while let _ = Performerposition(rawValue: maxValue) {         maxValue += 1    }    return maxValue}()static func randomPerformer() -> Performerposition {    // pick and return a new value    let rand = arc4random_uniform(UInt32(count))    return Playerposition(rawValue: Int(rand))!}

我怎么能这样做,所以我能够选择一个基于String_前缀的随机值,而不必求助于硬编码一个较高的值(例如,可以添加新的String_前缀位置)?谢谢

解决方法 因此,即使添加了新位置,您也不想更改任何代码.对?

要做到这一点,您需要动态获取所有枚举案例,而不是硬编码它们.根据this answer,您可以使用此方法来获取所有情况:

protocol EnumCollection : Hashable {}extension EnumCollection {    static func cases() -> AnySequence<Self> {        typealias S = Self        return AnySequence { () -> AnyIterator<S> in            var raw = 0            return AnyIterator {                let current : Self = withUnsafePointer(to: &raw) { 
let startingWithString = Array(Performerposition.cases().filter { "\()".hasPrefix("String_") })let rand = arc4random_uniform(UInt32(startingWithString.count))let randomposition = startingWithString[Int(rand)]
.withMemoryRebound(to: S.self,capacity: 1) { .pointee } } guard current.hashValue == raw else { return nil } raw += 1 return current } } }}

获得此案例方法后,您可以轻松获得所需内容:

总结

以上是内存溢出为你收集整理的swift – 从枚举的子部分中选择一个随机值全部内容,希望文章能够帮你解决swift – 从枚举的子部分中选择一个随机值所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1018749.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-23
下一篇 2022-05-23

发表评论

登录后才能评论

评论列表(0条)

保存