Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a string separated with new lines (\n) from an Array using Swift [duplicate]

I am facing a problem during the development of my iOS application, what I am trying to achieve is to create a single string from an array of strings. The array contains the address of a given location, obtained from a reverse geocoding using CLGeocoder, this is the code that gives me the array of strings:

let userCoordinates = CLLocation(latitude: mapView.userLocation.location!.coordinate.latitude, longitude: mapView.userLocation.location!.coordinate.longitude)

CLGeocoder().reverseGeocodeLocation(userCoordinates, completionHandler: {
    placemark, error in

    let reverseGeocodedLocation = placemark?.first?.addressDictionary?["FormattedAddressLines"] as? [String]
}

reverseGeocodedLocation in my case is:

["Apple Inc.", "Cupertino, CA  95014", "United States"]

The result string should separate the strings in the array and present them in a multi-line format like this:

Apple Inc.
Cupertino, CA 95014
United States

I have tried searching on the web for a solution and I found this code that should do that, and this could be the solution:

print("\n".join(reverseGeocodedLocation.map({$0})))

But the compiler says:

Cannot invoke 'join' with an argument list of type '([String]?)'

like image 859
Aluminum Avatar asked Apr 15 '26 02:04

Aluminum


1 Answers

if let reverseGeocodedLocation = reverseGeocodedLocation {
    print(reverseGeocodedLocation.joinWithSeparator("\n"))
}

As an answer instead of a comment.

Swift 3/4:

reverseGeocodedLocation.joined(separator: "\n")
like image 164
Henny Lee Avatar answered Apr 17 '26 16:04

Henny Lee