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 card app, did run into other problems but they were solved quickly.
To split a string to an array in Swift by a character, use the String. split(separator:) function.
reduce(_:_:) Returns the result of combining the elements of the sequence using the given closure.
To split a String by Character separator in Swift, use String. split() function. Call split() function on the String and pass the separator (character) as argument. split() function returns a String Array with the splits as elements.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With