In Swift, you can split a string into an array of substrings using split(separator:). It takes a character as the delimiter:
s.split(separator: delimiter) // splits using a delimiter character
Here are some examples:
let sentence = "hello world foo"
let words = sentence.split(separator: " ")
// words == ["hello", "world", "foo"]
let csv = "a,b,c"
let parts = csv.split(separator: ",")
// parts == ["a", "b", "c"]
You can loop through the resulting array:
for w in words {
print(w)
}
Assignment
Follow the Coding Tutorial and split sentence into a String array!
Hint
Use sentence.split(separator: " ") and assign the result to words.
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check