What's the Best Way to Shuffle an NSMutableArray?

后端 未结 12 1884
太阳男子
太阳男子 2020-11-21 11:53

If you have an NSMutableArray, how do you shuffle the elements randomly?

(I have my own answer for this, which is posted below, but I\'m new to Cocoa an

12条回答
  •  孤城傲影
    2020-11-21 12:24

    From iOS 10, you can use NSArray shuffled() from GameplayKit. Here is an helper for Array in Swift 3:

    import GameplayKit
    
    extension Array {
        @available(iOS 10.0, macOS 10.12, tvOS 10.0, *)
        func shuffled() -> [Element] {
            return (self as NSArray).shuffled() as! [Element]
        }
        @available(iOS 10.0, macOS 10.12, tvOS 10.0, *)
        mutating func shuffle() {
            replaceSubrange(0..

提交回复
热议问题