gpt4 book ai didi

swift - 为什么String.subscript(_ :) require the types `String.Index` and `Int` to be equal when there is no `Int` involved?

转载 作者:行者123 更新时间:2023-12-03 09:23:52 25 4
gpt4 key购买 nike

我无法理解Xcode在这一行面临的问题:

iteration.template = template[iterationSubstring.endIndex...substring.startIndex]
templateStringiterationSubstringsubstringSubstringtemplate。 Xcode用以下消息突​​出显示方括号:

Subscript 'subscript(_:)' requires the types 'Substring.Index' and 'Int' be equivalent



错误消息对我来说没有任何意义。我尝试通过使用 Substring下标创建 Range<String.Index>来获取 [template.startIndex...template.endIndex]。这和 Int有什么关系?为什么相同的模式在其他地方也起作用?

Xcode操场代码重现该问题:
import Foundation
let template = "This is an ordinary string literal."

let firstSubstringStart = template.index(template.startIndex, offsetBy: 5)
let firstSubstringEnd = template.index(template.startIndex, offsetBy: 7)
let firstSubstring = template[firstSubstringStart...firstSubstringEnd]

let secondSubstringStart = template.index(template.startIndex, offsetBy: 10)
let secondSubstringEnd = template.index(template.startIndex, offsetBy: 12)
let secondSubstring = template[secondSubstringStart...secondSubstringEnd]

let part: String = template[firstSubstring.endIndex...secondSubstring.startIndex]

毕竟,我有一个模板字符串和它的两个子字符串。我想要一个从第一个 String的结尾到第二个 Substring的开头的 Substring

最佳答案

Swift的当前版本可使用 Substring 结构(已切片的String)工作。

该错误似乎具有误导性,并且如果您要向Substring变量分配(带下标范围的)String,则会发生该错误。

要解决该错误,请从String创建一个Substring

iteration.template = String(template[iterationSubstring.endIndex...substring.startIndex])

但是,强烈建议您不要使用来自不同字符串( iterationSubstringsubstring)的索引来创建范围。切片主字符串,保留索引。

在第二个(同时删除)示例中发生崩溃是因为字符串的最后一个字符在 endIndex之前的索引处,它是
template[template.startIndex..<template.endIndex] 

或更短
template[template.startIndex...]

关于swift - 为什么String.subscript(_ :) require the types `String.Index` and `Int` to be equal when there is no `Int` involved?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60095464/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com