【发布时间】: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)。