假设我这里有一个字符串:

var fullName: String = "First Last"

我想在空白处拆分字符串,并将值分配给它们各自的变量

var fullNameArr = // something like: fullName.explode(" ") 

var firstName: String = fullNameArr[0]
var lastName: String? = fullnameArr[1]

此外,有时用户可能没有姓氏。


当前回答

我在寻找loosy拆分,例如PHP的分解,其中空序列包含在结果数组中,这对我很有用:

"First ".split(separator: " ", maxSplits: 1, omittingEmptySubsequences: false)

输出:

["First", ""]

其他回答

var fullName = "James Keagan Michael"
let first = fullName.components(separatedBy: " ").first?.isEmpty == false ? fullName.components(separatedBy: " ").first! : "John"
let last =  fullName.components(separatedBy: " ").last?.isEmpty == false && fullName.components(separatedBy: " ").last != fullName.components(separatedBy: " ").first ? fullName.components(separatedBy: " ").last! : "Doe"

不允许使用相同的名字和姓氏如果全名无效,则取占位符值“John Doe”

或者没有闭包,你可以在Swift 2中这样做:

let fullName = "First Last"
let fullNameArr = fullName.characters.split(" ")
let firstName = String(fullNameArr[0])

Swift 4、Xcode 10和iOS 12更新100%工作

let fullName = "First Last"    
let fullNameArr = fullName.components(separatedBy: " ")
let firstName = fullNameArr[0] //First
let lastName = fullNameArr[1] //Last

有关更多信息,请参阅此处的Apple文档。

假设您有一个名为“Hello World”的变量,如果您想将其拆分并存储为两个不同的变量,可以这样使用:

var fullText = "Hello World"
let firstWord = fullText.text?.components(separatedBy: " ").first
let lastWord = fullText.text?.components(separatedBy: " ").last

这是用于swift 4.2在20181206 1610的字符串和CSV文件

var dataArray : [[String]] = []
 let path = Bundle.main.path(forResource: "csvfilename", ofType: "csv")
        let url = URL(fileURLWithPath: path!)
        do {
            let data = try Data(contentsOf: url) 
            let content = String(data: data, encoding: .utf8)
            let parsedCSV = content?.components(separatedBy: "\r\n").map{ $0.components(separatedBy: ";") }
           for line in parsedCSV!
            {
                dataArray.append(line)
           }
        }
        catch let jsonErr {
            print("\n   Error read CSV file: \n ", jsonErr)
        }

            print("\n MohNada 20181206 1610 - The final result is \(dataArray)  \n ")