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

后端 未结 6 554
感动是毒
感动是毒 2020-12-30 02:43

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\

6条回答
  •  感动是毒
    2020-12-30 03:36

    try this

    var a = [1, 2, 3]    // Ints
    var s = ",".join(a.map { $0.description })
    

    or add this extension

    extension String {
        func join(elements: S) -> String {
            return self.join(map(elements){ $0.description })
        }
    
      // use this if you don't want it constrain to Printable
      //func join(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(elements: S) -> String
    }
    

    which means it takes a sequence of string, you can't pass a sequence of int to it.

提交回复
热议问题