0

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)" } 
6
  • 1
    Why did you make that string optional? Commented Oct 27, 2014 at 8:11
  • By mistake. I edited my question Commented Oct 27, 2014 at 8:18
  • It didn't work because you declared the titleAnswer as implicitly unwrapped optional. Now that you've turned into a non optional, it should work - see my answer below (there's also a better way to concatenate) Commented Oct 27, 2014 at 8:21
  • 1
    Does your code (after the edit) actually produce that error message? Otherwise your question is unclear. Commented Oct 27, 2014 at 8:25
  • @MartinR: You're right.i am getting empty string after concatenate operation. Commented Oct 27, 2014 at 8:37

2 Answers 2

5

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) 
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for explanation. It works. I am just started learning swift. I am not familiar with Optional Chaining. Will dig into it.
one more question. I want to display array of strings in multi line in a cell. How can i do that. can you guide me?
That's more complicated than just concatenating an array of strings. I suggest to search for a good tutorial, raywenderlich.com and appcoda.com have great ones
i thought of appending "\n" to string and display it in uilabel.
@Antonio, your solution be further reduced to: let res = string.reduce("", +)
1

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("", +) 

1 Comment

As of Swift 5, joined() - with no parameters achieves the same thing

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.