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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值