Swift相当于Array.componentsJoinedByString?

dev*_*os1 54 swift xcode6

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

'Array<String>' does not have a member named 'componentsJoinedByString'
Run Code Online (Sandbox Code Playgroud)

什么是逆componentsSeparatedByString斯威夫特?

Jac*_*nce 121

Swift 3.0:

与Swift 2.0类似,但API重命名已重命名joinWithSeparatorjoined(separator:).

let joinedString = ["1", "2", "3", "4", "5"].joined(separator: ", ")

// joinedString: String = "1, 2, 3, 4, 5" 
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参见Sequence.join(separator :).

Swift 2.0:

您可以使用该joinWithSeparator方法SequenceType将字符串数组与字符串分隔符连接起来.

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

// joinedString: String = "1, 2, 3, 4, 5" 
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅SequenceType.joinWithSeparator(_ :).

Swift 1.0:

您可以使用join标准库函数String来连接字符串数组和字符串.

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

// joinedString: String = "1, 2, 3, 4, 5" 
Run Code Online (Sandbox Code Playgroud)

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

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

// joinedString: String = "1, 2, 3, 4, 5"
Run Code Online (Sandbox Code Playgroud)


Con*_*nor 7

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

var nsarr = ["a", "b", "c"] as NSArray
var str = nsarr.componentsJoinedByString(",")
Run Code Online (Sandbox Code Playgroud)