Convert an array to a string in Swift

In this tutorial, we will learn how to convert an array into a string in Swift. This could help out in various tasks when dealing with arrays and strings in Swift. It can be easily done through .joined() method.

Array joined() method in Swift

This method concatenates the sequence of elements joined by a separator. The syntax for this would be-

array.joined(separator:Separator)

Convert array of strings into a string using joined() method

This method used the .joined() method to convert the array of strings into a string using separator-” “.

The snippet part includes-

let array=["This","is","an","array"]
let joinedstring=array.joined(separator:" ")
print(joinedstring)
print(type(of:joinedstring))

Output:-

This is an array.
String

In this method, we have created an array of strings and joined it with a separator ” ” and printed the type of Swift.

Convert array of characters into a string

This method converts an array of characters into a string. It follows the same above method as-

let array=["a","b","c","d"]
let joinedstring=array.joined(separator:" ")
print(joinedstring)
print(type(of:joinedstring))

Output-

a b c d
String

We can change the separator ” ” to “,” or “-“.

Convert array of integers into a string in Swift

This method converts array of integers into a string. It is quite different from the above methods and works for integers as-

let array=[1,2,3,4]
let joinedstring=array.map { String($0) }.joined(separator: " ")
print(joinedstring)
print(type(of:joinedstring))

Output-

1 2 3 4
String

This method just has one more step to map and then similarly joins the array of integers and converts to string.

Leave a Reply

Your email address will not be published. Required fields are marked *