當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Swift Unicode.Scalar init(_:)用法及代碼示例

用法一

初始化器

init(_:)

創建具有指定數值的 Unicode 標量。

聲明

init?(_ v: UInt16)

參數

v

用於標量的 Unicode 代碼點。如果 v 是有效的 Unicode 標量值,則初始化程序成功,範圍為 0...0xD7FF0xE000...0x10FFFF 。如果 v 是無效的 unicode 標量值,則結果為 nil

詳述

例如,以下代碼示例創建了一個 Unicode.Scalar 實例,其值為 "밥" ,韓語中的大米:


let codepoint: UInt16 = 48165
let bap = Unicode.Scalar(codepoint)
print(bap!)
// Prints "밥"

如果輸入值無效,則結果為 nil


let codepoint: UInt16 = extValue   // This might be an invalid value
if let bap = Unicode.Scalar(codepoint) {
    print(bap)
} else {
    // Do something else
}

可用版本

iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+

用法二

初始化器

init(_:)

創建具有指定數值的 Unicode 標量。

聲明

init(_ v: UInt8)

參數

v

用於標量的代碼點。

詳述

例如,以下代碼示例創建一個值為 "7"Unicode.Scalar 實例:


let codepoint: UInt8 = 55
let seven = Unicode.Scalar(codepoint)
print(seven)
// Prints "7"

可用版本

iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+

用法三

初始化器

init(_:)

創建具有指定數值的 Unicode 標量。

聲明

init?(_ v: Int)

參數

v

用於標量的 Unicode 代碼點。 v 必須是有效的 Unicode 標量值,在 0...0xD7FF0xE000...0x10FFFF 範圍內。如果 unicode 標量值無效,則返回 nil。

詳述

例如,以下代碼示例創建一個 Unicode.Scalar 實例,其值為表情符號字符:


let codepoint = 127881
let emoji = Unicode.Scalar(codepoint)!
print(emoji)
// Prints "🎉"

如果輸入值無效,則返回 nil。


let codepoint: UInt32 = extValue // This might be an invalid value.
if let emoji = Unicode.Scalar(codepoint) {
  print(emoji)
} else {
  // Do something else
}

可用版本

iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+

用法四

初始化器

init(_:)

創建具有指定數值的 Unicode 標量。

聲明

init?(_ v: UInt32)

參數

v

用於標量的 Unicode 代碼點。如果 v 是有效的 Unicode 標量值,即 v0...0xD7FF0xE000...0x10FFFF 範圍內,則初始化程序成功。如果 v 是無效的 Unicode 標量值,則結果為 nil

詳述

例如,以下代碼示例創建一個 Unicode.Scalar 實例,其值為表情符號字符:


let codepoint: UInt32 = 127881
let emoji = Unicode.Scalar(codepoint)
print(emoji!)
// Prints "🎉"

如果輸入值無效,則返回 nil。


let codepoint: UInt32 = extValue   // This might be an invalid value
if let emoji = Unicode.Scalar(codepoint) {
  print(emoji)
} else {
  // Do something else
}

可用版本

iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+

相關用法


注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 Unicode.Scalar init(_:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。