A position in a String
or one of its views.
あるString
またはそれのビューの1つの中のある位置。
init(_:within:)
UTF16View
position.
与えられたUTF-8ビューの中のあるインデックスを作成します、それは指定されたUTF16View
位置に正確に対応します。
Availability
- iOS 8.0+
- iPadOS 8.0+
- macOS 10.10+
- Mac Catalyst 13.0+
- tvOS 9.0+
- watchOS 2.0+
- Xcode 9.0+
Technology
- Swift Standard Library Swift標準ライブラリ
Declaration 宣言
Parameters パラメータ
sourcePosition
target
The
UTF8View
in which to find the new position. それにおいて新しい位置を見つけるUTF8View
。
Discussion 解説
The following example finds the position of a space in a string’s utf16
view and then converts that position to an index in the string’s utf8
view.
以下の例は、ある空白の位置を文字列のもつutf16
ビューの中で見つけて、それからその位置を文字列のもつutf8
ビューの中のインデックスに変換します。
let cafe = "Café 🍵"
let utf16Index = cafe.utf16.firstIndex(of: 32)!
let utf8Index = String.UTF8View.Index(utf16Index, within: cafe.utf8)!
print(Array(cafe.utf8[..<utf8Index]))
// Prints "[67, 97, 102, 195, 169]"
If the position passed in utf16Index
doesn’t have an exact corresponding position in utf8
, the result of the initializer is nil
. For example, because UTF-8 and UTF-16 represent high Unicode code points differently, an attempt to convert the position of the trailing surrogate of a UTF-16 surrogate pair fails.
utf16Index
に渡された位置がまさにその対応する位置をutf8
において持たないならば、イニシャライザの結果はnil
です。例えば、UTF-8とUTF-16は高位ユニコードコード点を異なって表すので、UTF-16のサロゲートペアの後続サロゲートの位置を変換する試みは失敗します。
The next example attempts to convert the indices of the two UTF-16 code points that represent the teacup emoji ("🍵"
). The index of the lead surrogate is successfully converted to a position in utf8
, but the index of the trailing surrogate is not.
次の例は、ティーカップ絵文字("🍵"
)を表す2つのUTF-16コード点のインデックスの変換を試みます。先頭サロゲートはうまくutf8
での位置に変換されます、しかし後続サロゲートのインデックスは違います。
let emojiHigh = cafe.utf16.index(after: utf16Index)
print(String.UTF8View.Index(emojiHigh, within: cafe.utf8))
// Prints "Optional(String.Index(...))"
let emojiLow = cafe.utf16.index(after: emojiHigh)
print(String.UTF8View.Index(emojiLow, within: cafe.utf8))
// Prints "nil"