Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 ?

like image 399
Ken Zhang Avatar asked Aug 30 '14 10:08

Ken Zhang


People also ask

How do you split a string into an individual character in Swift?

The String. split() Function. To split a string into an array in Swift, use the String. split() function.

How do you make an array of strings in Swift?

To convert an array to string in Swift, call Array. joined() function.


2 Answers

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"
like image 200
Jonauz Avatar answered Jan 01 '23 14:01

Jonauz


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.

like image 29
Bryan Chen Avatar answered Jan 01 '23 13:01

Bryan Chen