Concatenate String in Swift

2019-03-03 14:10发布

问题:

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)"
 }

回答1:

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)


回答2:

In Swift 3, this is how you join elements of a String array:

 ["this", "is", "a", "string"].joined(separator: "")

Although, joined(separator:) is really geared for actually putting a separator between the strings. Reduce is still more concise:

 ["this", "is", "a", "string"].reduce("", +)