將字串拆分為陣列

在 Swift 中,你可以通過將 String 切片為某個字元,輕鬆地將 String 分隔為陣列:

Version = 3.0

let startDate = "23:51"

let startDateAsArray = startDate.components(separatedBy: ":") // ["23", "51"]`

Version = 2.2

let startDate = "23:51"

let startArray = startDate.componentsSeparatedByString(":") // ["23", "51"]`

或者當分隔符不存在時:

Version = 3.0

let myText = "MyText"

let myTextArray = myText.components(separatedBy: " ") // myTextArray is ["MyText"]

Version = 2.2

let myText = "MyText"

let myTextArray = myText.componentsSeparatedByString(" ") // myTextArray is ["MyText"]