SwiftSwift开发iOS学习

Swift 3必看:集合方法flatten()重命名为joine

2016-09-10  本文已影响1270人  没故事的卓同学

<code>flatten</code>的作用之一可以将集合里的类型为集合的值连接起来。直接看例子:

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

// 结果为[1,2,3]  

但是如果数组元素为String时,有一个特别的方法<code>joined(separator:)</code>,作用也是将集合里的元素连接起来(只是元素必须是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
}

显然针对过去<code>flatten</code>的使用方式,它的真实意图就是join。所以在swift 3中,将<code>flatten()</code>重命名为<code>joined()</code>。
这么一来可读性也提高了。也增加了一种使用方法:在连接集合内元素时可以指定连接的元素。比如:

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

上一篇下一篇

猜你喜欢

热点阅读