有人可以解释为什么半开放和关闭范围在Swift 3中的字符串上不再相同吗?
此代码有效:
var hello = "hello"
let start = hello.index(hello.startIndex, offsetBy: 1)
let end = hello.index(hello.startIndex, offsetBy: 4)
let range = start..<end // <-- Half Open Range Operator still works
let ell = hello.substring(with: range)
但这不是:
var hello = "hello"
let start = hello.index(hello.startIndex, offsetBy: 1)
let end = hello.index(hello.startIndex, offsetBy: 4)
let range = start...end // <-- Closed Range Operator does NOT work
let ello = hello.substring(with: range) // ERROR
导致如下错误:
Cannot convert value of type 'ClosedRange<String.Index>' (aka 'ClosedRange<String.CharacterView.Index>') to expected argument type 'Range<String.Index>' (aka 'Range<String.CharacterView.Index>')
答案 0 :(得分:2)
要执行您要执行的操作,请不要致电substring(with:)
。直接下标:
var hello = "hello"
let start = hello.index(hello.startIndex, offsetBy: 1)
let end = hello.index(hello.startIndex, offsetBy: 4)
let ello = hello[start...end] // "ello"
答案 1 :(得分:0)
let range = start..<end
有效? NSRange
(described here), substring(with:)
就是您所需要的。
以下是Range
的{{3}}:
相比类型的半开区间,从下限到, 但不包括上限。
创建Range
:
您可以使用半开放范围运算符创建Range实例 (..≤)。
所以波纹管代码完全正确(它会起作用):
var hello = "hello"
let start = hello.index(hello.startIndex, offsetBy: 1)
let end = hello.index(hello.startIndex, offsetBy: 4)
let range = start..<end // <-- Half Open Range Operator still works
let ell = hello.substring(with: range)
let range = start...end
不起作用:如果吼叫,你强迫ClosedRange
成为Range
:
var hello = "hello"
let start = hello.index(hello.startIndex, offsetBy: 1)
let end = hello.index(hello.startIndex, offsetBy: 4)
let range = start...end // <-- Closed Range Operator does NOT work
let ello = hello.substring(with: range) // ERROR
ClosedRange
转换为Range
?