Swift相当于Array.componentsJoinedByString?

时间:2014-07-13 21:13:06

标签: swift xcode6

在Objective-C中,我们可以调用componentsJoinedByString来生成一个字符串,该数组的每个元素由提供的字符串分隔。虽然Swift在String上有componentsSeparatedByString方法,但在数组上似乎没有这个方法的反转:

'Array<String>' does not have a member named 'componentsJoinedByString'

Swift中componentsSeparatedByString的倒数是什么?

2 个答案:

答案 0 :(得分:120)

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:)

Swift 2.0:

您可以使用joinWithSeparator上的SequenceType方法通过字符串分隔符连接字符串数组。

let joinedString = ["1", "2", "3", "4", "5"].joinWithSeparator(", ")

// joinedString: String = "1, 2, 3, 4, 5" 

有关详细信息,请参阅SequenceType.joinWithSeparator(_:)

Swift 1.0:

您可以使用join上的String标准库函数来加入带字符串的字符串数组。

let joinedString = ", ".join(["1", "2", "3", "4", "5"])

// joinedString: String = "1, 2, 3, 4, 5" 

或者,如果您更愿意,可以使用全局标准库函数:

let joinedString = join(", ", ["1", "2", "3", "4", "5"])

// joinedString: String = "1, 2, 3, 4, 5"

答案 1 :(得分:7)

componentsJoinedByString在NSArray上仍然可用,但在Swift Arrays上不可用。你可以来回桥接。

var nsarr = ["a", "b", "c"] as NSArray
var str = nsarr.componentsJoinedByString(",")