Append unichar to NSMutableString in Swift

1.1k views Asked by At

I want to append a unichar to NSMutableString. I have

var outputString: NSMutableString = "Some string" 
let letterA: unichar = 0x1820

I saw the question Appending unichar to NSMutableString. The accepted answer (in Objective C) says:

[s appendFormat:@"%C", c];

but I can't figure out the Swift syntax. The documentation doesn't help much, either.

I even tried

outputString += letterA

but that also didn't work.

Note: I'm not trying to append a Swift String or append a Swift Character.

3

There are 3 answers

1
Nofel Mahmood On BEST ANSWER

Use the same method appendFormat in swift like this

Rewriting your code to elaborate

    var outputString: NSMutableString = "Some string"
    let letterA: unichar = 0x1820
    outputString.appendFormat("%C", letterA)
0
Rikki Gibson On

outputString.appendFormat("%C", letterA) appends the character in Swift 1.2 running in Xcode 6.4. It appears to be the same method you've referenced in the Objective-C sample.

3
SwiftArchitect On

NSMutableString

The NSMutableString reference does not need to be a var

let outputString:NSMutableString = "Some string"
outputString.appendFormat("%C", 0x0041) // Letter A

Native Swift String

Solution skipping NSFoundation and unichar classes:

var outputString = "Some string"
outputString += "\u{41}" // Letter A is actually 0x0041