How do I shuffle an array in Swift?

前端 未结 25 2615
长发绾君心
长发绾君心 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:40

    Here's some code that runs in playground. You won't need to import Darwin in an actual Xcode project.

    import darwin
    
    var a = [1,2,3,4,5,6,7]
    
    func shuffle(item1: ItemType, item2: ItemType) -> Bool {
        return drand48() > 0.5
    }
    
    sort(a, shuffle)
    
    println(a)
    

提交回复
热议问题