for example:
var a = [1, 2, 3] // Ints
var s = ",".join(a) // EXC_BAD_ACCESS
Is it possible to make the join function return "1,2,3" ?
Extend Int (or other custom types) to conform to some protocols ?
The String. split() Function. To split a string into an array in Swift, use the String. split() function.
To convert an array to string in Swift, call Array. joined() function.
From Xcode 7.0 beta 6 in Swift 2 now you should use [String].joinWithSeparator(",")
.
In your case you still need to change Int to String type, therefore I added map()
.
var a = [1, 2, 3] // [1, 2, 3]
var s2 = a.map { String($0) }.joinWithSeparator(",") // "1,2,3"
From Xcode 8.0 beta 1 in Swift 3 code slightly changes to
[String].joined(separator: ",")
.
var s3 = a.map { String($0) }.joined(separator: ",") // "1,2,3"
try this
var a = [1, 2, 3] // Ints
var s = ",".join(a.map { $0.description })
or add this extension
extension String {
func join<S : SequenceType where S.Generator.Element : Printable>(elements: S) -> String {
return self.join(map(elements){ $0.description })
}
// use this if you don't want it constrain to Printable
//func join<S : SequenceType>(elements: S) -> String {
// return self.join(map(elements){ "\($0)" })
//}
}
var a = [1, 2, 3] // Ints
var s = ",".join(a) // works with new overload of join
join is defined as
extension String {
func join<S : SequenceType where String == String>(elements: S) -> String
}
which means it takes a sequence of string, you can't pass a sequence of int to it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With