如果你想按给定的值分割一个字符串特点那么你可以使用
内置split()
方法,无需基础:
let str = "Today is so hot"
let arr = split(str, { $0 == " "}, maxSplit: Int.max, allowEmptySlices: false)
println(arr) // [Today, is, so, hot]
Swift 1.2 更新:参数的顺序与Swift 1.2(Xcode 6.3)改变了,比较split 现在抱怨缺少“isSeparator” https://stackoverflow.com/questions/28726774/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]
Swift 2 更新: See 斯图尔特的回答 https://stackoverflow.com/a/31906777/1187415.
Swift 3 更新:
let str = "Today is so hot"
let arr = str.characters.split(separator: " ").map(String.init)
print(arr)