当前位置 : 主页 > 手机开发 > 其它 >

swift – 打印时如何摆脱数组括号

来源:互联网 收集:自由互联 发布时间:2021-06-11
打印数组时如何摆脱左右括号? var array = ["1", "2", "3", "4"]println("\(array)") //It prints [1, 2, 3, 4]var arrayWithoutBracketsAndCommas = array. //some codeprintln("\(arrayWithoutBracketsAndCommas)") //prints 1 2 3 4 你可以
打印数组时如何摆脱左右括号?

var array = ["1", "2", "3", "4"]
println("\(array)") //It prints [1, 2, 3, 4]

var arrayWithoutBracketsAndCommas = array. //some code

println("\(arrayWithoutBracketsAndCommas)") //prints 1 2 3 4
你可以这样做:

extension Array {
    var minimalDescription: String {
        return " ".join(map { "\($0)" })
    }
}

["1", "2", "3", "4"].minimalDescription // "1 2 3 4"

使用Swift 2,使用Xcode b6,来自SequenceType的joinWithSeparator方法:

extension SequenceType where Generator.Element == String {
    ...
    public func joinWithSeparator(separator: String) -> String
}

你能做的意思是:

extension SequenceType {
    var minimalDescrption: String {
        return map { String($0) }.joinWithSeparator(" ")
    }
}

[1, 2, 3, 4].minimalDescrption // "1 2 3 4"

斯威夫特3:

extension Sequence {
    var minimalDescription: String {
        return map { "\($0)" }.joined(separator: " ")
    }
}
网友评论