How to split an array in half in Swift?

前端 未结 5 1833
醉梦人生
醉梦人生 2021-02-06 23:26

How do I split a deck of cards? I have an array made and a random card dealer, but have no idea how to split the deck.

Thanks everyone for the help! I now have a working

5条回答
  •  广开言路
    2021-02-07 00:17

    You can use subscript range

    let deck: [String] = ["J", "Q", "K", "A"]
    
    // use ArraySlice only for transient computation
    let leftSplit: ArraySlice = deck[0 ..< deck.count / 2] // "J", "Q"
    let rightSplit: ArraySlice = deck[deck.count / 2 ..< deck.count] // "K", "A"
    
    // make arrays from ArraySlice
    let leftDeck: [String] = Array(leftSplit) // "J", "Q"
    let rightDeck: [String] = Array(rightSplit) // "K", "A"
    

    EDIT: above code is for Swift 2, maybe for Swift 3 is a more convenient way.

提交回复
热议问题