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

var fullName: String = "First Last"

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

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

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

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


当前回答

这在Beta 5中再次发生了变化。哭泣!它现在是CollectionType上的一个方法

旧版本:

var fullName = "First Last"
var fullNameArr = split(fullName) {$0 == " "}

新建:

var fullName = "First Last"
var fullNameArr = fullName.split {$0 == " "}

苹果发行说明

其他回答

这直接提供了一个分割部分的数组

var fullNameArr = fullName.components(separatedBy:" ")

那么你可以这样使用,

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

对于swift 2,XCode 7.1:

let complete_string:String = "Hello world"
let string_arr =  complete_string.characters.split {$0 == " "}.map(String.init)
let hello:String = string_arr[0]
let world:String = string_arr[1]

斯威夫特4

let words = "these words will be elements in an array".components(separatedBy: " ")

在解释Don Vaughn的答案时,我喜欢使用正则表达式。我很惊讶这只是Regex的第二个答案。然而,如果我们能用一个拆分方法而不是多个方法来解决这个问题,那就太好了。

我也受到了米特拉·辛加姆(Mithra Singam)的《答案》(Answer)的启发,排除了所有标点符号和空格。然而,不得不创建一个不允许的角色列表并没有引起我的共鸣。

\w-字母或数字符号的正则表达式。没有标点符号。

let foo = "(..#   Hello,,(---- World   ".split {
    String($0).range(of: #"\w"#, options: .regularExpression) == nil
}
print(foo) // Prints "Hello World"

让我们假设你对Unicode不太满意。ASKII字母和数字怎么样?

let bar = "(..#   Hello,,(---- World   ".split {
    !($0.isASCII && ($0.isLetter || $0.isNumber))
}
print(bar) // Prints "Hello World"

非顶部:

对于搜索如何使用子字符串(而不是字符)拆分字符串的人来说,下面是一个有效的解决方案:

// TESTING
let str1 = "Hello user! What user's details? Here user rounded with space."
let a = str1.split(withSubstring: "user") // <-------------- HERE IS A SPLIT
print(a) // ["Hello ", "! What ", "\'s details? Here ", " rounded with space."]

// testing the result
var result = ""
for item in a {
    if !result.isEmpty {
        result += "user"
    }
    result += item
}
print(str1) // "Hello user! What user's details? Here user rounded with space."
print(result) // "Hello user! What user's details? Here user rounded with space."
print(result == str1) // true

/// Extension providing `split` and `substring` methods.
extension String {
    
    /// Split given string with substring into array
    /// - Parameters:
    ///   - string: the string
    ///   - substring: the substring to search
    /// - Returns: array of components
    func split(withSubstring substring: String) -> [String] {
        var a = [String]()
        var str = self
        while let range = str.range(of: substring) {
            let i = str.distance(from: str.startIndex, to: range.lowerBound)
            let j = str.distance(from: str.startIndex, to: range.upperBound)
            let left = str.substring(index: 0, length: i)
            let right = str.substring(index: j, length: str.length - j)
            a.append(left)
            str = right
        }
        if !str.isEmpty {
            a.append(str)
        }
        return a
    }
    
    /// the length of the string
    public var length: Int {
        return self.count
    }
    
    /// Get substring, e.g. "ABCDE".substring(index: 2, length: 3) -> "CDE"
    ///
    /// - parameter index:  the start index
    /// - parameter length: the length of the substring
    ///
    /// - returns: the substring
    public func substring(index: Int, length: Int) -> String {
        if self.length <= index {
            return ""
        }
        let leftIndex = self.index(self.startIndex, offsetBy: index)
        if self.length <= index + length {
            return String(self[leftIndex..<self.endIndex])
        }
        let rightIndex = self.index(self.endIndex, offsetBy: -(self.length - index - length))
        return String(self[leftIndex..<rightIndex])
    }

}