Unicode

设定值

直接使用 Unicode

var str: String = "I want to visit 北京, Москва, मुंबई, القاهرة, and 서울시. 😊"
var character: Character = "🌍"

使用十六进制值

var str: String = "\u{61}\u{5927}\u{1F34E}\u{3C0}" // a 大🍎π
var character: Character = "\u{65}\u{301}" // é = "e" + accent mark

请注意,Swift Character 可以由多个 Unicode 代码点组成,但看起来是单个字符。这称为扩展字形集群。

转换

字符串 - >十六进制

// Accesses views of different Unicode encodings of `str`
str.utf8
str.utf16
str.unicodeScalars // UTF-32

十六进制 - >字符串

let value0: UInt8 = 0x61
let value1: UInt16 = 0x5927
let value2: UInt32 = 0x1F34E

let string0 = String(UnicodeScalar(value0)) // a
let string1 = String(UnicodeScalar(value1)) // 大
let string2 = String(UnicodeScalar(value2)) // 🍎

// convert hex array to String
let myHexArray = [0x43, 0x61, 0x74, 0x203C, 0x1F431] // an Int array
var myString = ""
for hexValue in myHexArray {
    myString.append(UnicodeScalar(hexValue))
}
print(myString) // Cat‼🐱

请注意,对于 UTF-8 和 UTF-16,转换并不总是那么容易,因为像表情符号这样的东西不能用单个 UTF-16 值编码。它需要一个代理对。