Split a String into an array in Swift?
Just call componentsSeparatedByString
method on your fullName
import Foundationvar fullName: String = "First Last"let fullNameArr = fullName.componentsSeparatedByString(" ")var firstName: String = fullNameArr[0]var lastName: String = fullNameArr[1]
Update for Swift 3+
import Foundationlet fullName = "First Last"let fullNameArr = fullName.components(separatedBy: " ")let name = fullNameArr[0]let surname = fullNameArr[1]
The Swift way is to use the global split
function, like so:
var fullName = "First Last"var fullNameArr = split(fullName) {$0 == " "}var firstName: String = fullNameArr[0]var lastName: String? = fullNameArr.count > 1 ? fullNameArr[1] : nil
with Swift 2
In Swift 2 the use of split becomes a bit more complicated due to the introduction of the internal CharacterView type. This means that String no longer adopts the SequenceType or CollectionType protocols and you must instead use the .characters
property to access a CharacterView type representation of a String instance. (Note: CharacterView does adopt SequenceType and CollectionType protocols).
let fullName = "First Last"let fullNameArr = fullName.characters.split{$0 == " "}.map(String.init)// or simply:// let fullNameArr = fullName.characters.split{" "}.map(String.init)fullNameArr[0] // FirstfullNameArr[1] // Last
The easiest method to do this is by using componentsSeparatedBy:
For Swift 2:
import Foundationlet fullName : String = "First Last";let fullNameArr : [String] = fullName.componentsSeparatedByString(" ")// And then to access the individual words:var firstName : String = fullNameArr[0]var lastName : String = fullNameArr[1]
For Swift 3:
import Foundationlet fullName : String = "First Last"let fullNameArr : [String] = fullName.components(separatedBy: " ")// And then to access the individual words:var firstName : String = fullNameArr[0]var lastName : String = fullNameArr[1]