在Swift中将字符串拆分成数组? [英] 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.
推荐答案
Swift方法是使用全局split
函数,如下所示:
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
使用 Swift 2
在Swift 2中,由于引入了内部CharacterView类型,对split的使用变得更加复杂.这意味着String不再采用SequenceType或CollectionType协议,而必须使用.characters
属性访问String实例的CharacterView类型表示. (注意:CharacterView确实采用SequenceType和CollectionType协议.)
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
这篇关于在Swift中将字符串拆分成数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!