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

相关文章
相关标签/搜索