How do I shuffle an array in Swift?

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

    Swift 4 Shuffle the elements of an array in a for loop where i is the mixing ratio

    var cards = [Int]() //Some Array
    let i = 4 // is the mixing ratio
    func shuffleCards() {
        for _ in 0 ..< cards.count * i {
            let card = cards.remove(at: Int(arc4random_uniform(UInt32(cards.count))))
            cards.insert(card, at: Int(arc4random_uniform(UInt32(cards.count))))
        }
    }
    

    Or with extension Int

    func shuffleCards() {
        for _ in 0 ..< cards.count * i {
            let card = cards.remove(at: cards.count.arc4random)
            cards.insert(card, at: cards.count.arc4random)
        }
    }
    extension Int {
        var arc4random: Int {
            if self > 0 {
                print("Arc for random positiv self \(Int(arc4random_uniform(UInt32(self))))")
            return Int(arc4random_uniform(UInt32(self)))
            } else if self < 0 {
                print("Arc for random negotiv self \(-Int(arc4random_uniform(UInt32(abs(self)))))")
                return -Int(arc4random_uniform(UInt32(abs(self))))
            } else {
                print("Arc for random equal 0")
                return 0
            }
        }
    }
    

提交回复
热议问题