Method

作者: partrick | 来源:发表于2016-12-22 10:27 被阅读0次

    joined

    有时,将数组或字典以特定格式输出到控制台,便于擦看数据的变化。
    数组的方法就可以做到。

    let array = [1, 2, 3]
    let description = array.joined()
    error: ambiguous reference to member 'joined()'

    文档里只说joined是Array的method,错误提示又说找不到。swift是对类型及其严格的语言,这里马上怀疑是类型的问题。可是文档里没有任何明确的说明。
    于是看Command click,看代码。

    extension Array where Element == String {
        public func joined(separator: String = default) -> String
    }
    

    Array的Element必须是String。

    let array = [1, 2, 3]
    let description = array.map({ String($0) }).joined()
    print(description)
    

    输出

    123

    也可以加分割符

    let array = [1, 2, 3]
    let description = array.map({ String($0) }).joined(separator: " | ")
    print(description)
    

    1 | 2 | 3

    相关文章

      网友评论

          本文标题:Method

          本文链接:https://www.haomeiwen.com/subject/exbcvttx.html