【问题标题】:How can I gave custom Index to String.Index working with unicode in Swift?如何在 Swift 中使用 unicode 为 String.Index 提供自定义索引?
【发布时间】:2021-03-01 11:08:32
【问题描述】:

我想为我的代码提供一个自定义索引,这意味着自定义字符串/字符可以在该空间位置读取该字符串的 unicodeScalars,例如,此向下代码适用于 string.startIndex 但我无法将它更改为我想要的索引,即使代码在运行时为 string.endIndex 给出错误所以我需要帮助,现在这个向下代码仅适用于字符串的索引零,例如我想要这个工作对于 index = 1 这意味着 B,我该怎么做?

let string: String = "ABC"
let UInt32Value: UInt32 = string.unicodeScalars[string.startIndex].value
print(UInt32Value)

更新:你可以用customIndex替换string.startIndex

let index: Int = 1
let customIndex: String.Index = string.index(string.startIndex, offsetBy: index)

仍然需要帮助了解原因 string.endIndex 不起作用!?!

【问题讨论】:

  • 索引 unicode 标量的方式与索引字符串的方式相同。见stackoverflow.com/questions/24092884/…
  • @Sweeper,感谢您的帮助,更多的是关于使用字符串长度或类似的东西,但我得到了我想要的,
  • 至于string.endIndex为什么不起作用:string.endIndex是索引结束位置,所以如果你需要字符串最后一个元素的索引,你需要index(endIndex, offsetBy: -1)

标签: swift string


【解决方案1】:

您可以在String 上创建一个扩展,将索引作为String.IndexInt,然后使用它来下标unicodeScalars

extension String {
    func unicodeScalarValue(at index: String.Index) -> UInt32 {
        unicodeScalars[index].value
    }
    
    func unicodeScalarValue(at index: Int) -> UInt32 {
        unicodeScalars[self.index(startIndex, offsetBy: index)].value
    }
}

"ABC".unicodeScalarValue(at: 0)
"ABC".unicodeScalarValue(at: 1)
"ABC".unicodeScalarValue(at: 2)

【讨论】:

    猜你喜欢
    • 2017-02-02
    • 1970-01-01
    • 2019-09-01
    • 2019-12-23
    • 2018-07-08
    • 2014-03-12
    • 1970-01-01
    • 1970-01-01
    • 2013-11-01
    相关资源
    最近更新 更多