How to access a random element in a dictionary in Swift

后端 未结 3 1394
深忆病人
深忆病人 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:22

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

    Either randomElement:

    let randomVal = myDict.values.randomElement()
    

    Or randomElement:

    let randomVal = myDict.randomElement().value
    

提交回复
热议问题