xcode 从变量打印 unicode 字符(swift)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31696142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 07:34:39  来源:igfitidea点击:

Print unicode character from variable (swift)

xcodeswiftunicode

提问by yesman82

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 .

我有一个问题,我找不到解决办法。我有一个包含 unicode "1f44d" 的字符串变量,我想将其转换为 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.

应该想象 charAsString 的值来自 API 调用或来自另一个对象。

采纳答案by Jakub Vano

This can be done in two steps:

这可以分两步完成:

  1. convert charAsStringto Intcode
  2. convert code to unicode character
  1. 转换charAsStringInt代码
  2. 将代码转换为 unicode 字符

Second step can be done e.g. like this

第二步可以像这样完成

var code = 0x1f44d
var scalar = UnicodeScalar(code)
var string = "\(scalar)"

As for first the step, see herehow to convert Stringin hex representation to Int

对于第一步,请参阅此处如何将String十六进制表示转换为Int

回答by Martin R

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:

使用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.

另请注意,并非所有代码点都是有效的 Unicode 标量,请比较Swift 中的 Validate Unicode code point



Update for Swift 3:

Swift 3更新

public init?(_ v: UInt32)

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

现在是一个可失败的初始化器,UnicodeScalar并检查给定的数字输入是否是有效的 Unicode 标量值:

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

回答by Fantattitude

As of Swift 2.0, every Inttype has an initializer able to take Stringas an input. You can then easily generate an UnicodeScalarcorresponding and print it afterwards. Without having to change your representation of chars as string ;).

从 Swift 2.0 开始,每种Int类型都有一个可以String作为输入的初始化器。然后,您可以轻松生成UnicodeScalar相应的并在之后打印。无需将字符表示更改为字符串;)。

UPDATED: Swift 3.0 changed UnicodeScalar initializer

更新:Swift 3.0 更改了 UnicodeScalar 初始值设定项

print("\u{1f44d}") // 

let charAsString = "1f44d" // code in variable

let charAsInt = Int(charAsString, radix: 16)! // As indicated by @MartinR radix is required, default won't do it
let uScalar = UnicodeScalar(charAsInt)! // In Swift 3.0 this initializer is failible so you'll need either force unwrap or optionnal unwrapping

print("\(uScalar)")

回答by hkdalex

Here are a couple ways to do it:

这里有几种方法可以做到:

let string = "1f44d"

Solution 1:

解决方案1:

"&#x\(string);".applyingTransform(.toXMLHex, reverse: true)

Solution 2:

解决方案2:

"U+\(string)".applyingTransform(StringTransform("Hex/Unicode"), reverse: true)

回答by Avinash

You can use

您可以使用

let char = "-12"
print(char.unicodeScalars.map {
[45, 49, 50]
.value }))

You'll get the values as:

您将获得以下值:

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

回答by Imanou Petit

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

当您尝试使用它时,您不能在 Swift 中使用字符串插值。因此,以下代码将无法编译:

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

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:

您必须将字符串变量转换为整数(使用init(_:radix:)初始化程序),然后从该整数创建一个 Unicode 标量。下面的 Swift 5 Playground 示例代码显示了如何继续:

##代码##