How to get random element from a set in Swift?

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

    If you want a 'random' element from a Set then you use:

    /// A member of the set, or `nil` if the set is empty.
    var first: T? { get }
    

    Get the 0th index or the 1,000,000th index makes no difference - they are all an arbitrary object.

    But, if you want repeated calls to return a likely different element each time, then first might not fit the bill.

提交回复
热议问题