问题描述
在 Objective-C 中,我们可以调用 componentsJoinedByString
来生成一个字符串,其中数组的每个元素由提供的字符串分隔.虽然 Swift 在 String 上有一个 componentsSeparatedByString
方法,但在 Array 上似乎没有相反的方法:
In Objective-C we can call componentsJoinedByString
to produce a string with each element of the array separated by the supplied string. While Swift has a componentsSeparatedByString
method on String, there doesn't appear to be the inverse of this on Array:
'Array<String>' does not have a member named 'componentsJoinedByString'
Swift 中 componentsSeparatedByString
的逆是什么?
What is the inverse of componentsSeparatedByString
in Swift?
推荐答案
Swift 3.0:
类似于 Swift 2.0,但 API 重命名已将 joinWithSeparator
重命名为 joined(separator:)
.
let joinedString = ["1", "2", "3", "4", "5"].joined(separator: ", ")
// joinedString: String = "1, 2, 3, 4, 5"
请参阅 Sequence.join(separator:) 了解更多信息.
See Sequence.join(separator:) for more information.
您可以使用 SequenceType
上的 joinWithSeparator
方法将字符串数组与字符串分隔符连接起来.
You can use the joinWithSeparator
method on SequenceType
to join an array of strings with a string separator.
let joinedString = ["1", "2", "3", "4", "5"].joinWithSeparator(", ")
// joinedString: String = "1, 2, 3, 4, 5"
请参阅 SequenceType.joinWithSeparator(_:) 了解更多信息.
See SequenceType.joinWithSeparator(_:) for more information.
您可以使用 String
上的 join
标准库函数将字符串数组与字符串连接起来.
You can use the join
standard library function on String
to join an array of strings with a string.
let joinedString = ", ".join(["1", "2", "3", "4", "5"])
// joinedString: String = "1, 2, 3, 4, 5"
或者,如果您愿意,可以使用全局标准库函数:
Or if you'd rather, you can use the global standard library function:
let joinedString = join(", ", ["1", "2", "3", "4", "5"])
// joinedString: String = "1, 2, 3, 4, 5"
这篇关于Swift 相当于 Array.componentsJoinedByString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!