Home > Back-end >  Ambiguous use of 'init' in Array mapped to String with chosen separators
Ambiguous use of 'init' in Array mapped to String with chosen separators

Time:01-12

As @vadian suggested, I am learning Xcode from Paul Hudson's 100 days of SwiftUI to better understand the basics (even though I am still struggling with time to deliver working GitHub repository search - no it is not for the job I am working on right now).

I am doing a lesson on Arrays, so pretty basic stuff right now and I struggle to map the String from array on the sorted array. I don't get why, but I get the:

Ambiguous use of 'init'

error.

Here's the code:

let cities = ["London", "Tokyo", "Rome", "Budapest"]
print(cities.sorted())

let citiesSorted = cities.sorted()

let citiesSortedString = citiesSorted.map(String.init).joined(separator:", ")

And it's so really strange, since I pulled the similar thing out before in the same Playground but not with the sorted Array:

var schoolScoresString = schoolScores.map(String.init).joined(separator:", ")
print(schoolScoresString)

And yes I tried changing let to var. It didn't help.

CodePudding user response:

cities is already of type [String], so you're passing a String to String.init, which obviously won't work. If you want to join an array of Strings into a single String, remove the map and just call joined on the array.

let citiesSortedString = citiesSorted.joined(separator:", ")
  •  Tags:  
  • Related