15

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

6
  • it works for me ... ????? Commented Sep 23, 2017 at 10:26
  • It is working :) Commented Sep 23, 2017 at 10:33
  • update my question see the pic Commented Sep 23, 2017 at 10:36
  • Why you have used flatMap ? Could u describe what would you like to achive ? Commented Sep 23, 2017 at 10:38
  • 3
    As a rule of thumb, String(describing:) is almost never what you want (even if the compiler suggests it as a Fix-it). Commented Sep 23, 2017 at 11:38

1 Answer 1

20

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()).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks it's working.Please also add the source in the answer if you have.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.