Bright
Bright

Reputation: 5751

How to use split and map method?

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?

Upvotes: 0

Views: 800

Answers (1)

66o
66o

Reputation: 756

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!

Upvotes: 3

Related Questions