Swift 3必看:集合方法flatten()重命名爲joined()

flatten的做用之一能夠將集合裏的類型爲集合的值鏈接起來。直接看例子:git

[[1,2],[3]].flatten()              

// 結果爲[1,2,3]複製代碼

可是若是數組元素爲String時,有一個特別的方法joined(separator:),做用也是將集合裏的元素鏈接起來(只是元素必須是String) 看定義:github

extension Array where Element == String {

    /// Returns a new string by concatenating the elements of the sequence,
    /// adding the given separator between each element.
    ///
    /// The following example shows how an array of strings can be joined to a
    /// single, comma-separated string:
    ///
    /// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
    /// let list = cast.joined(separator: ", ")
    /// print(list)
    /// // Prints "Vivien, Marlon, Kim, Karl"
    ///
    /// - Parameter separator: A string to insert between each of the elements
    /// in this sequence. The default separator is an empty string.
    /// - Returns: A single, concatenated string.
    public func joined(separator: String = default) -> String
}複製代碼

顯然針對過去flatten的使用方式,它的真實意圖就是join。因此在swift 3中,將flatten()重命名爲joined()。 這麼一來可讀性也提升了。也增長了一種使用方法:在鏈接集合內元素時能夠指定鏈接的元素。好比:swift

let nestedNumbers = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
let joined = nestedNumbers.join(separator: [-1, -2])
print(Array(joined))
// Prints "[1, 2, 3, -1, -2, 4, 5, 6, -1, -2, 7, 8, 9]"複製代碼

相關連接:數組

SE0133-Rename flatten() to joined() A (mostly) comprehensive list of Swift 3.0 and 2.3 changesapp

相關文章
相關標籤/搜索