iPhone Guy iPhone Guy - 3 months ago 8
iOS Question

Concatenate String in Swift

i have an array which contains strings i.e Array

i tried to concatenate string, but i got an error as "String is not identical to UInt8"

var titleString:String! = ""

for title in array {
titleString += "\(title)"
}

Answer

To concatenate all elements of a string array, you can use the reduce method:

var string = ["this", "is", "a", "string"]

let res = string.reduce("") { $0 + $1 }

The first parameter is the initial string, which is empty, and the second is a closure, which is executed for each element in the array. The closure receives 2 parameters: the value returned at the previous step (or the initial value, if it's the 1st element), and the current element value.

More info here

Addendum I forgot to explicitly answer to your question: the concatenation doesn't work because you declared the titleString as optional - just turn into a non optional variable and it will work. If you still want to use the optional, then use forced unwrapping when doing the assignment:

titleString! += "\(title)"

Addendum 2 As suggested by @MartinR, there's another simpler way to concatenate:

join("", string)