Antiokhos Antiokhos - 7 months ago 159
Swift Question

Swift version of componentsSeparatedByString

I know its noob question, i really search around before ask. But there is not exact answer of what i want to know.
How we split string into the array without using Objective C? For example:

var str = "Today is so hot"
var arr = str.componentsSeparatedByString(" ") // *



  • I know it doesnt work but i am looking for like that. I want to split string with " " (or another char/string)



Idea:It might be very good for me, making extension of string class. But i dont know how i do that.

Edit: Forgetting import Foundation. If I import foundation it will work. But is there any way to do with extending String class?
Thank you

Answer

If you want to split a string by a given character then you can use the built-in split() method, without needing Foundation:

let str = "Today is so hot"
let arr = split(str, { $0 == " "}, maxSplit: Int.max, allowEmptySlices: false)
println(arr) // [Today, is, so, hot]

Update for Swift 1.2: The order of the parameters changed with Swift 1.2 (Xcode 6.3), compare split now complains about missing "isSeparator":

let str = "Today is so hot"
let arr = split(str, maxSplit: Int.max, allowEmptySlices: false, isSeparator: { $0 == " "} )
println(arr) // [Today, is, so, hot]

Update for Swift 2: See Stuart's answer.