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

沒故事的卓同學發表於2019-03-03

flatten的作用之一可以將集合裡的型別為集合的值連線起來。直接看例子:

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

// 結果為[1,2,3]複製程式碼

但是如果陣列元素為String時,有一個特別的方法joined(separator:),作用也是將集合裡的元素連線起來(只是元素必須是String) 看定義:

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()。 這麼一來可讀性也提高了。也增加了一種使用方法:在連線集合內元素時可以指定連線的元素。比如:

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 changes

相關文章