Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

xcode - Print unicode character from variable (swift)

I have a problem I couldn't find a solution to. I have a string variable holding the unicode "1f44d" and I want to convert it to a unicode character ??.

Usually one would do something like this:

println("u{1f44d}") // ??

Here is what I mean:

let charAsString = "1f44d" // code in variable
println("u{(charAsString)}") // not working

I have tried several other ways but somehow the workings behind this magic stay hidden for me.

One should imagine the value of charAsString coming from an API call or from another object.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One possible solution (explanations "inline"):

let charAsString = "1f44d"

// Convert hex string to numeric value first:
var charCode : UInt32 = 0
let scanner = NSScanner(string: charAsString)
if scanner.scanHexInt(&charCode) {

    // Create string from Unicode code point:
    let str = String(UnicodeScalar(charCode))
    println(str) // ??
} else {
    println("invalid input")
}

Slightly simpler with Swift 2:

let charAsString = "1f44d"

// Convert hex string to numeric value first:
if let charCode = UInt32(charAsString, radix: 16) {
    // Create string from Unicode code point:
    let str = String(UnicodeScalar(charCode))
    print(str) // ??
} else {
    print("invalid input")
}

Note also that not all code points are valid Unicode scalars, compare Validate Unicode code point in Swift.


Update for Swift 3:

public init?(_ v: UInt32)

is now a failable initializer of UnicodeScalar and checks if the given numeric input is a valid Unicode scalar value:

let charAsString = "1f44d"

// Convert hex string to numeric value first:
if let charCode = UInt32(charAsString, radix: 16),
    let unicode = UnicodeScalar(charCode) {
    // Create string from Unicode code point:
    let str = String(unicode)
    print(str) // ??
} else {
    print("invalid input")
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...