Welcome to OGeek Q&A 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 Reply

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")
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...