Ken Zhang Ken Zhang - 5 months ago 13
Swift Question

Swift: how can String.join() work custom types?

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 ?

Answer

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.

Comments