How to access a random element in a dictionary in Swift

后端 未结 3 1384
深忆病人
深忆病人 2021-02-13 14:30

I got the following code:

var myDic = [String: Customer]()
let s1 = Customer(\"nameee\", \"email1\")
let s2 = Customer(\"nameee2\", \"email2\")
let s3 = Customer         


        
相关标签:
3条回答
  • 2021-02-13 15:19

    Swift 5+ (Xcode 12+) introduces randomise Dictionary key also

    let randomVal = myDict.randomElement()?.key
    
    0 讨论(0)
  • 2021-02-13 15:22

    Swift 4.2+ (Xcode 10+) introduces two simple possibilities.

    Either randomElement:

    let randomVal = myDict.values.randomElement()
    

    Or randomElement:

    let randomVal = myDict.randomElement().value
    
    0 讨论(0)
  • 2021-02-13 15:35

    You have to cast some things around, but this seems to work.

    var dict:[String:Int] = ["A":123, "B": 234, "C": 345]
    let index: Int = Int(arc4random_uniform(UInt32(dict.count)))
    let randomVal = Array(dict.values)[index] # 123 or 234 or 345
    

    Basically, generate a random index value between zero and the total item count. Get the values of the dictionary as an array and then fetch the random index.

    You could even wrap that in an extension for easy access.

    0 讨论(0)
提交回复
热议问题