Print unicode character from variable (swift)

前端 未结 6 451
耶瑟儿~
耶瑟儿~ 2020-11-30 14:53

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

6条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 15:35

    You cannot use string interpolation in Swift as you try to use it. Therefore, the following code won't compile:

    let charAsString = "1f44d"
    print("\u{\(charAsString)}")
    

    You will have to convert your string variable into an integer (using init(_:radix:) initializer) then create a Unicode scalar from this integer. The Swift 5 Playground sample code below shows how to proceed:

    let validCodeString = "1f44d"
    let validUnicodeScalarValue = Int(validCodeString, radix: 16)!
    let validUnicodeScalar = Unicode.Scalar(validUnicodeScalarValue)!
    print(validUnicodeScalar) // 

提交回复
热议问题