Pet*_*ter 9 xcode foundation swift
我无法理解 Xcode 在这一行中遇到的问题:
iteration.template = template[iterationSubstring.endIndex...substring.startIndex]
Run Code Online (Sandbox Code Playgroud)
template
是一个String
和iterationSubstring
和substring
是Substring
第template
。Xcode 使用以下消息突出显示左方括号:
下标 'subscript(_:)' 要求类型 'Substring.Index' 和 'Int' 是等价的
错误消息对我来说没有任何意义。我尝试Substring
通过Range<String.Index>
使用[template.startIndex...template.endIndex]
下标创建 a来获得 a 。这与 有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]
Run Code Online (Sandbox Code Playgroud)
毕竟我有一个模板字符串和它的两个子字符串。我想获得String
从第一个结尾Substring
到第二个开头的范围Substring
。
vad*_*ian 11
当前版本的 Swift 使用Substring
切片的struct String
。
该错误似乎具有误导性,如果您要将(范围下标)Substring
分配给String
变量。
要修复错误,请String
从Substring
iteration.template = String(template[iterationSubstring.endIndex...substring.startIndex])
Run Code Online (Sandbox Code Playgroud)
然而,强烈建议您不要使用来自不同字符串 (iterationSubstring
和substring
) 的索引创建范围。切片主字符串,保留索引。
第二个(同时已删除)示例中的崩溃发生是因为字符串的最后一个字符位于索引之前endIndex
,它是
template[template.startIndex..<template.endIndex]
Run Code Online (Sandbox Code Playgroud)
或更短
template[template.startIndex...]
Run Code Online (Sandbox Code Playgroud)