Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split an array in half in Swift?

Tags:

arrays

swift

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.

like image 604
Irrafoxy Avatar asked Aug 18 '15 13:08

Irrafoxy


People also ask

How do you split an array in Swift?

To split a string to an array in Swift by a character, use the String. split(separator:) function.

What is reduce in Swift?

reduce(_:_:) Returns the result of combining the elements of the sequence using the given closure.

How do I split a string into words in Swift?

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.


1 Answers

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.

like image 176
Eric Aya Avatar answered Oct 07 '22 16:10

Eric Aya