Search code examples
arraysswiftswift4

How to join an array of strings into a single string Swift 4


Prior to Swift 4 I used the code below to join an array of strings into a single string:

let array = ["Andrew", "Ben", "John", "Paul", "Peter", "Laura"]
let joined = array.joined(separator: ", ")

 //output:- "Andrew, Ben, John, Paul, Peter, Laura"

But now in Swift 4 and Xcode 9 is showing one of the following errors:

Ambiguous reference to member 'joined()'

Value of type 'TYPE' has no member 'join'

How can I join all elements of an array? Was the syntax changed in Swift 4?

enter image description here


Solution

  • That's a typical example where pseudo-code in the question is misleading and doesn't reproduce the error.

    The error occurs because you are using flatMap. Since the array is a non-optional single-level array of Int just use map and don't use the describing initializer:

    func getNumbers(array : [Int]) -> String {
        let stringArray = array.map( String.init )
        return stringArray.joined(separator: ",")
    }
    

    The ambiguity is that flatMap applied to an non-optional sequence has a different meaning:

    From the documentation

    let numbers = [1, 2, 3, 4]
    
    let mapped = numbers.map { Array(count: $0, repeatedValue: $0) } 
    // [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]
    
    let flatMapped = numbers.flatMap { Array(count: $0, repeatedValue: $0) }
     // [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
    

    In fact, s.flatMap(transform) is equivalent to Array(s.map(transform).joined()).