【发布时间】:2020-05-22 12:41:14
【问题描述】:
我无法理解 Xcode 在这一行中遇到的问题:
iteration.template = template[iterationSubstring.endIndex...substring.startIndex]
template 是 String 和 iterationSubstring 和 substring 是 Substrings 的 template。 Xcode 使用以下消息突出显示左方括号:
下标 'subscript(_:)' 要求类型 'Substring.Index' 和 'Int' 等价
错误消息对我没有任何意义。我尝试通过创建带有[template.startIndex...template.endIndex] 下标的Range<String.Index> 来获得Substring。这与Int 有什么关系?为什么相同的模式在其他地方也有效?
Xcode Playground 代码重现问题:
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 的开头。
【问题讨论】:
-
您的财产
template是什么类型的?似乎它被声明为String。主要问题是使用ClosedRange而不是Range和类型不匹配试图将Substring分配给String或两者的组合。尝试let part: String = template[template.startIndex...template.endIndex]会抛出Subscript 'subscript(_:)' requires the types 'String.Index' and 'Int' be equivalent -
@MartinR 我更新了操场代码以在第一个 sn-p 中重现我的问题。
-
@LeoDabus
template确实是String。我忘了提那个。事实上,这是一个明显的类型不匹配。哎呀。 Xcode 真的让我分心了。
标签: swift xcode foundation