本文翻译自:Split a String into an array in Swift?
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. 同样,有时用户可能没有姓氏。
#1楼
参考:https://stackoom.com/question/1jk7J/在Swift中将字符串拆分成数组
#2楼
The easiest method to do this is by using componentsSeparatedBy: 最简单的方法是使用componentsSeparatedBy:
For Swift 2: 对于Swift 2:
import Foundation
let 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: 对于Swift 3:
import Foundation
let fullName : String &#