In today's tutorial, you learn how to convert an array to a string in Swift. The Foundation framework defines a few APIs we can use. Which API you use largely depends on the type of the elements of the array. Let's get started.
Creating a Playground
Fire up Xcode and create a playground by choosing the Blank template from the iOS > Playground section. Remove the contents of the playground. Add an import statement for the Foundation framework.
import Foundation
Converting an Array of Strings to a String
Let's start with an array of String
objects. That is the simplest scenario I can think of. We declare a constant with name fruits
and use it to store an array of strings.
import Foundation
let fruits = [
"apple",
"orange",
"cherry",
"strawberry"
]
To convert the array to a string, we call the joined()
method on the array. The joined()
method returns a string by concatenating the elements of the array.
import Foundation
let fruits = [
"apple",
"orange",
"cherry",
"strawberry"
]
fruits.joined() // appleorangecherrystrawberry
The result is a string, but it is probably not what you wanted or even expected. The joined()
method defines an optional parameter, separator
of type String
. If we want to separate the elements of the array with a comma, then we pass a comma as the separator.
import Foundation
let fruits = [
"apple",
"orange",
"cherry",
"strawberry"
]
fruits.joined() // appleorangecherrystrawberry
fruits.joined(separator: ",") // apple,orange,cherry,strawberry
Converting an Array of Objects to a String
What do you do if the elements of the array are objects or dictionaries? The idea remains the same, but we need to take one additional step. Take the following example. We declare a struct with name Movie
. We create an array of Movie
objects and store it in a constant with name movies
.
import Foundation
struct Movie {
let title: String
let releaseDate: Int
}
let movies = [
Movie(title: "Harry Potter and the Sorcerer's Stone", releaseDate: 2001),
Movie(title: "Harry Potter and the Chamber of Secrets", releaseDate: 2002),
Movie(title: "Harry Potter and the Prisoner of Azkaban", releaseDate: 2004),
Movie(title: "Harry Potter and the Goblet of Fire", releaseDate: 2005),
Movie(title: "Harry Potter and the Order of the Phoenix", releaseDate: 2007),
Movie(title: "Harry Potter and the Half-Blood Prince", releaseDate: 2009),
Movie(title: "Harry Potter and the Deathly Hallows – Part 1", releaseDate: 2010),
Movie(title: "Harry Potter and the Deathly Hallows – Part 2", releaseDate: 2011),
]
If we call joined()
on the array of movies, the compiler throws an error. The joined(separator:)
method is only available if the sequence, a set or an array, has elements of type String
.
The solution is simple, though. We use the map(_:)
method to convert the array of movies to an array of strings. Let's say we want to extract the movie titles from the array, then we call the map(_:)
method on the array of movies and return the movie title from the closure we pass to the map(_:)
method. Once the array of Movie
objects is converted to an array of String
objects, we can use the joined(separator:)
method to convert the array to a string.
movies.map { movie in
movie.title
}.joined(separator: ",")
Converting an Array of Dictionaries to a String
Let's take is one step further and convert an array of dictionaries to a string. Take a look at the following example.
import Foundation
let movies = [
["title": "Harry Potter and the Sorcerer's Stone", "releaseDate": 2001],
["title": "Harry Potter and the Chamber of Secrets", "releaseDate": 2002],
["title": "Harry Potter and the Prisoner of Azkaban", "releaseDate": 2004],
["title": "Harry Potter and the Goblet of Fire", "releaseDate": 2005],
["title": "Harry Potter and the Order of the Phoenix", "releaseDate": 2007],
["title": "Harry Potter and the Half-Blood Prince", "releaseDate": 2009],
["title": "Harry Potter and the Deathly Hallows – Part 1", "releaseDate": 2010],
["title": "Harry Potter and the Deathly Hallows – Part 2", "releaseDate": 2011]
]
The movies
array no longer consists of Movie
objects. We replaced the Movie
objects with dictionaries. This isn't an approach I recommend, but let's use this example to illustrate how to convert an array of dictionaries to a string.
The solution is similar to the one we used for the array of Movie
objects. We call the map(_:)
method on the array to extract the movie title and use the joined(separator:)
method to convert the array of strings the map(_:)
method returns to a string.
movies.map { movie in
movie["title"]
}.joined(separator: ",")
There is another problem and it illustrates why I recommend using a struct instead of dictionary to define a movie.
The dictionaries the array contains are of type [String: Any]
and that means we need to cast the title to a String
. This in turn means we need to deal with optionals. The Foundation framework has a solution, though. We use the compactMap(_:)
method instead of the map(_:)
method to filter out nil
values.
movies.compactMap { movie in
movie["title"] as? String
}.joined(separator: ",")
I use the compactMap(_:)
method a lot in situations like this. I keeps the code I write clean and readable. Take a look at How to Use Swift Map to Transform Arrays, Sets, and Dictionaries if you want to learn more about the map(_:)
method.