How do I convert a Swift array to a string?


Let's look at some examples of how to convert an array to a string.

Method 1:Using Joined(seperator:)

Syntax

Swift provides us with a method joined(separator:) of an array that can be used to convert a Swift array to a string. This method returns a new string by concatenating the elements of the array, separated by the provided separator string.

let wordInString = words.joined(separator: ", ")

In order to use the joined() method, call it by array along with passing the separator whatever you want.

Algorithm

  • Step 1 − Initialize your array

  • Step 2 − Call joined() method with element separator

  • Step 3 − Store the result in a new variable

Example

Here's an example of how you might use joined(separator:) to convert an array of strings to a single string −

let words = ["one", "two", "three", "four", "five"]
let wordInString = words.joined(separator: ", ")
print("Array =",words)
print("Converted String=",wordInString)

Output

Array = ["one", "two", "three", "four", "five"]
Converted String= one, two, three, four, five

Method 2:Using String Initializer

Syntax

You can also use joined(separator:) to convert an array of integers or other types to a string. In this case, you'll need to make sure that the elements of the array can be converted to strings using the String initializer.

let numberString = numbers.map { String($0) }.joined(separator: ", ")

The map() function is used to convert each number into a string, and the elements of the resulting array from the map() function are joined with the help of joined() function.

Algorithm

  • Step 1 − Initialize your array

  • Step 2 − Convert each integer into the string using the map() function

  • Step 3 − Join them using joined() function.

  • Step 4 − Store the result in the new variable

For Example

let numbers = [10, 20, 30, 40, 50]
let numberString = numbers.map { String($0) }.joined(separator: ", ")
print("Converted String =", numberString)

Output

Converted String = 10, 20, 30, 40, 50

This code first uses the map method to convert the elements of the numbers array to strings, and then uses joined(separator:) to concatenate the strings into a single string, separated by commas and spaces.

Conclusion

Many times, you need to convert the Swift array into a string. For this, you can use the joined() function.

Updated on: 03-Jan-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements