how to join array in swift

To join an array in Swift, you can use the joined() method. This method returns a string composed of the elements of the array, in the order they appear, joined using a specified separator.

Here's an example:

main.swift
let array = ["apple", "banana", "orange"]
let joinedString = array.joined(separator: ", ")

print(joinedString) // Output: "apple, banana, orange"
147 chars
5 lines

Alternatively, you can use the reduce(_:_:) method to concatenate the elements of the array, like so:

main.swift
let array = ["apple", "banana", "orange"]
let concatenatedString = array.reduce("") { "\($0), \($1)" }.dropFirst()

print(concatenatedString) // Output: "apple, banana, orange"
177 chars
5 lines

In the above code, reduce(_:_:) is used with an initial value of an empty string "". The closure takes two arguments, $0 and $1, which represent the current accumulated string and the current element of the array. The closure then returns a new string which is the concatenation of the two, with a comma and space separator. The dropFirst() method is called to remove the initial separator from the final string.

gistlibby LogSnag