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.swift147 chars5 lines
Alternatively, you can use the reduce(_:_:)
method to concatenate the elements of the array, like so:
main.swift177 chars5 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