How to convert array into a string by delimiter in swift example

This tutorial explains multiple ways to convert an Array of elements into a String in Swift with examples. There are multiple ways to convert Array into a String

  • use Joined function
  • map with joined function
  • Array map with reduce function

Sometimes, We have an array of strings that you want to combine using a separator. This tutorial helps you with multiple ways to combine it.

Convert Array into a String with delimiter in Swift

There are multiple ways we can do it.

  • Use Array joined the function Arrays.joined function provides to combine array elements with given separator.

You can give any separator or delimiter such as hyphen, comma, etc.

Here is an example

let numbers = ["one", "two", "three"]
let result = numbers.joined(separator: "-")

print(result)

Output:

one-two-three

The above example works in Swift 4 version.

  • Use Array map with a joined function

Another way using the map function which iterates an array of elements and constructs string objects, calling joined to return the combined string.

let numbers = ["one", "two", "three"]

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

print(result)
  • Use Array map with a reduced function

map function used to iterate each element an array and append using reduce function

let numbers = ["one", "two", "three"]
let result = numbers.map {"\($0)"}.reduce(" ") { $0 + $1 }
print(result)

Output:

onetwothree