0

I saw a question: Swift: Split a String into an array

And there's some code I don't understand:

let fullName = "First Last"
let fullNameArr = split(fullName.characters){$0 == " "}.map{String($0)}

fullNameArr[0] // First
fullNameArr[1] // Last

How does split() and map{} work?

Community
  • 1
  • 1
Bright
  • 5,699
  • 2
  • 50
  • 72
  • Both are documented in the Swift Standard Library Reference: [SequenceType Protocol Reference](https://developer.apple.com/library/ios//documentation/Swift/Reference/Swift_SequenceType_Protocol/index.html#//apple_ref/swift/intf/s:PSs12SequenceType). You can also option-click on the method name in Xcode for a quick help. – Martin R Oct 13 '15 at 11:29
  • @MartinR the official document is inhumanly hard to understand for learners, I have no idea how it works under the hood. – Bright Oct 13 '15 at 11:40

1 Answers1

3

You're using a syntax that won't work in Xcode7. The correct syntax should be

let fullNameArr = fullName.characters.split{$0 == " "}.map(String.init)

Getting that out of the way let's break down that line into two pieces:

split takes

A collection of Characters representing the String's extended grapheme clusters

-- From Xcode docs

and a closure taking a character and returning Bool - true if the character can be considered as a separator.

if this syntax is confusing try reading that:

  fullNameArr = fullName.characters.split({
    character in
    return character == " "
  })

Now, split returns an array of SubSequence objects. You want to convert them back to string to be able to print them nicely. So one way of doing it would be creating a for loop iterating over all the results of split and converting them to string, then appending to a result array, or using map method that does the same.

If you look closely at the first line, you execute map on the array and pass a closure that does something with every element of the array and writes it back.

A simple example how that works

let exampleArray = [1, 2, 3]
print(exampleArray.map {$0 * 3})

// prints [3, 6, 9]

Hope that helps!

66o
  • 756
  • 5
  • 10