gpt4 book ai didi

swift - 打印时如何去掉数组括号

转载 作者:搜寻专家 更新时间:2023-10-31 21:52:38 27 4
gpt4 key购买 nike

打印数组时如何去除左右括号?

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"

swift 3:

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

关于swift - 打印时如何去掉数组括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31093678/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com