How to get random element from a set in Swift?

前端 未结 6 993
别那么骄傲
别那么骄傲 2021-01-04 06:41

As of Swift 1.2, Apple introduces Set collection type.

Say, I have a set like:

var set = Set(arrayLiteral: 1, 2, 3, 4, 5)
         


        
6条回答
  •  無奈伤痛
    2021-01-04 06:47

    extension Set {
        func randomElement() -> Element? {
            return count == 0 ? nil : self[advance(self.startIndex, Int(arc4random()) % count)]
        }
    }
    

提交回复
热议问题