How to split an array in half in Swift?

前端 未结 5 1755
醉梦人生
醉梦人生 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:26

    You can make an extension so it can return an array of two arrays, working with Ints, Strings, etc:

    extension Array {
        func split() -> [[Element]] {
            let ct = self.count
            let half = ct / 2
            let leftSplit = self[0 ..< half]
            let rightSplit = self[half ..< ct]
            return [Array(leftSplit), Array(rightSplit)]
        }
    }
    
    let deck = ["J", "Q", "K", "A"]
    let nums = [0, 1, 2, 3, 4]
    
    deck.split() // [["J", "Q"], ["K", "A"]]
    nums.split() // [[0, 1], [2, 3, 4]]
    

    But returning a named tuple is even better, because it enforces the fact that you expect exactly two arrays as a result:

    extension Array {
        func split() -> (left: [Element], right: [Element]) {
            let ct = self.count
            let half = ct / 2
            let leftSplit = self[0 ..< half]
            let rightSplit = self[half ..< ct]
            return (left: Array(leftSplit), right: Array(rightSplit))
        }
    }
    
    let deck = ["J", "Q", "K", "A"]
    
    let splitDeck = deck.split()
    print(splitDeck.left) // ["J", "Q"]
    print(splitDeck.right) // ["K", "A"]
    

    Note: credits goes to Andrei and Qbyte for giving the first correct answer, I'm just adding info.

提交回复
热议问题