How do I shuffle an array in Swift?

前端 未结 25 2272
长发绾君心
长发绾君心 2020-11-21 05:44

How do I randomize or shuffle the elements within an array in Swift? For example, if my array consists of 52 playing cards, I want to shuffle the array in o

25条回答
  •  故里飘歌
    2020-11-21 06:36

    This is what I use:

    func newShuffledArray(array:NSArray) -> NSArray {
        var mutableArray = array.mutableCopy() as! NSMutableArray
        var count = mutableArray.count
        if count>1 {
            for var i=count-1;i>0;--i{
                mutableArray.exchangeObjectAtIndex(i, withObjectAtIndex: Int(arc4random_uniform(UInt32(i+1))))
            }
        }
        return mutableArray as NSArray
    }
    

提交回复
热议问题