How to get random element from a set in Swift?

前端 未结 6 1012
别那么骄傲
别那么骄傲 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:56

    In swift 3

    extension Set {
        public func randomObject() -> Element? {
            let n = Int(arc4random_uniform(UInt32(self.count)))
            let index = self.index(self.startIndex, offsetBy: n)
            return self.count > 0 ? self[index] : nil
        }
    }
    

提交回复
热议问题