How to append a character to a string in Swift?
append append(c: Character)
IS the right method but your code has two other problems.
The first is that to iterate over the characters of a string you must access the String.characters
property.
The second is that the append method doesn't return anything so you should remove the newStr.
The code then looks like this:
for aCharacter : Character in aString.characters {
var str:String = ""
str.append(aCharacter)
// ... do other stuff
}
Another possible option is
var s: String = ""
var c: Character = "c"
s += "\(c)"
This also works
var newStr:String = str + String(aCharacter)
Update for the moving target that is Swift:
Swift no longer has a + operator that can take a String and an array of characters. (There is a string method appendContentsOf()
that can be used for this purpose).
The best way of doing this now is Martin R’s answer in a comment below:
var newStr:String = str + String(aCharacter)
Original answer: This changed in Beta 6. Check the release notes.I'm still downloading it, but try using:
var newStr:String = str + [aCharacter]