Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append a character to a string in Swift?

Tags:

string

swift

This used to work in Xcode 6: Beta 5. Now I'm getting a compilation error in Beta 6.

for aCharacter: Character in aString {     var str: String = ""     var newStr: String = str.append(aCharacter) // ERROR     ... } 

Error: Cannot invoke append with an argument of type Character

like image 575
samatron Avatar asked Aug 23 '14 01:08

samatron


People also ask

How do I add characters to a string in Swift?

for aCharacter: Character in aString { var str: String = "" var newStr: String = str. append(aCharacter) // ERROR ... }

Can you append to a string Swift?

You can't append a String or Character to an existing Character variable, because a Character value must contain a single character only.

How do I get the first character of a string in Swift?

In Swift, the first property is used to return the first character of a string.

What is string interpolation in Swift?

Swift String Interpolation 2) Means the string is created from a mix of constants, variables, literals or expressions. Example: let length:Float = 3.14 var breadth = 10 var myString = "Area of a rectangle is length*breadth" myString = "\(myString) i.e. = \(length)*\(breadth)"


2 Answers

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] 
like image 141
Gary Makin Avatar answered Sep 20 '22 19:09

Gary Makin


This also works

var newStr:String = str + String(aCharacter) 
like image 24
baskInEminence Avatar answered Sep 21 '22 19:09

baskInEminence