swift - 为什么 String.subscript(_:) 在不涉及 `Int` 的情况下要求 `String.Index` 和 `Int` 类型相等?
问题描述
我无法理解 Xcode 在这一行中遇到的问题:
iteration.template = template[iterationSubstring.endIndex...substring.startIndex]
template
是 aString
并且是siterationSubstring
的。Xcode 使用以下消息突出显示左方括号:substring
Substring
template
下标 '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
。
解决方案
当前版本的 Swift 使用 slice 的Substring
struct String
。
Substring
如果您要将(范围下标)分配给String
变量,则该错误似乎具有误导性。
要修复错误String
,请从Substring
iteration.template = String(template[iterationSubstring.endIndex...substring.startIndex])
尽管如此,强烈建议您不要使用来自不同字符串(iterationSubstring
和substring
)的索引创建范围。切片主字符串,索引被保留。
第二个(同时删除)示例中的崩溃发生是因为字符串的最后一个字符位于索引 beforeendIndex
,它是
template[template.startIndex..<template.endIndex]
或更短
template[template.startIndex...]
推荐阅读
- python - 加入列中的单词列表
- python-3.x - col.drop_duplicates() 有更快的替代方法吗?
- excel - VBA 从 Internet 源下载图像
- go - 为什么我无法使用在不同包中定义的结构?
- java - REST JAX-RS 自定义上下文提供程序不起作用
- python - 合并子图错误 - 'AxesSubplot' 对象没有属性 'get_gridspec'
- android - 安卓摇篮。如何将 Flavors 与 buildTypes 结合起来
- spring-boot - Spring Cloud Config 客户端发送错误的 Basic Auth 标头
- reactjs - Mobx-react : 默认不再是一部分
- java - 使用 Spring Boot Test 运行测试