String.Index(quo:在:)初始值设定项崩溃

String.Index(quo:在:)初始值设定项崩溃,string,swift,String,Swift,最近我一直在乱搞String索引,我很难弄清楚事情的来龙去脉,有些东西仍然让我感到困扰 我正在尝试使用init(:within:)类型为String.Index的方法。当我在字符串的边界内使用utf16index时,它工作得非常好,但在字符串的边界外,它会因以下消息而崩溃: 致命错误:此UnicodeScalar视图的String.utf16索引无效 现在,我得到了文档中所述的功能要求: /// - Requires: `utf16Index` is an element of /// `c

最近我一直在乱搞
String
索引,我很难弄清楚事情的来龙去脉,有些东西仍然让我感到困扰

我正在尝试使用
init(:within:)
类型为
String.Index的方法。当我在字符串的边界内使用
utf16index
时,它工作得非常好,但在字符串的边界外,它会因以下消息而崩溃:

致命错误:此UnicodeScalar视图的String.utf16索引无效

现在,我得到了文档中所述的功能要求:

/// - Requires: `utf16Index` is an element of
///   `characters.utf16.indices`.
实际问题:我不明白的是,当这个
init
是一个失败的初始值设定项时,为什么会崩溃?它是否应该返回
nil


我可能会做一个方法来检查索引是否可以在字符串中,但对我来说仍然很奇怪。

该方法的完整标题文档是

extension String.CharacterView.Index {

    // ...

    public init?(_ unicodeScalarIndex: UnicodeScalarIndex, within characters: String)
    /// Construct the position in `characters` that corresponds exactly to
    /// `utf16Index`. If no such position exists, the result is `nil`.
    ///
    /// - Requires: `utf16Index` is an element of
    ///   `characters.utf16.indices`.
    public init?(_ utf16Index: UTF16Index, within characters: String)

    // ...

}
因此,有两种不同的失败原因:

  • 给定的
    utf16Index
    超出了
    characters.utf16
    。这违反了要求并导致运行时中断 例外
  • 给定的
    utf16Index
    字符的有效索引。utf16
    ,但是 没有与该索引对应的字符位置。 在这种情况下,该方法返回
    nil

作为一个例子,考虑字符串“aI非常确定这与字符占用不止一个UTF16代码单元有关,而您真正完整的答案很好地解释了这一点。非常感谢;)事实上,我在写作时忽略了这个要求,在阅读了你的问题后,我现在就修正了它。@MartinR很有趣,因为我的问题最初是由我来实现你对这个问题的解决方案的!