Say I have a string here:
var fullName: String = "First Last"
I want to split the string base on white space and assign the values to their respective variables
var fullNameArr = // something like: fullName.explode(" ") var firstName: String = fullNameArr[0] var lastName: String? = fullnameArr[1]
Also, sometimes users might not have a last name.
To split a string to an array in Swift by a character, use the String. split(separator:) function. However, this requires that the separator is a singular character, not a string.
Swift String split() The split() method breaks up a string at the specified separator and returns an array of strings.
Null Character ( \0 )
reduce(_:_:) Returns the result of combining the elements of the sequence using the given closure.
Just call componentsSeparatedByString
method on your fullName
import Foundation var fullName: String = "First Last" let fullNameArr = fullName.componentsSeparatedByString(" ") var firstName: String = fullNameArr[0] var lastName: String = fullNameArr[1]
Update for Swift 3+
import Foundation let 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] // First fullNameArr[1] // Last
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With