首页 > 解决方案 > 为什么 String.subscript(_:) 在不涉及 `Int` 的情况下要求 `String.Index` 和 `Int` 类型相等?

问题描述

我无法理解 Xcode 在这一行中遇到的问题:

iteration.template = template[iterationSubstring.endIndex...substring.startIndex]

template是 aString并且是siterationSubstring的。Xcode 使用以下消息突​​出显示左方括号:substringSubstringtemplate

下标 'subscript(_:)' 要求类型 'Substring.Index' 和 'Int' 等价

错误消息对我没有任何意义。我尝试通过使用下标Substring创建 a来获得 a 。这有什么关系?为什么相同的模式在其他地方也有效?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

标签: swiftxcodefoundation

解决方案


当前版本的 Swift 使用 slice 的Substringstruct String

Substring如果您要将(范围下标)分配给String变量,则该错误似乎具有误导性。

要修复错误String,请从Substring

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

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


第二个(同时删除)示例中的崩溃发生是因为字符串的最后一个字符位于索引 beforeendIndex,它是

template[template.startIndex..<template.endIndex] 

或更短

template[template.startIndex...]

推荐阅读