Swift Strings上的范围运算符(..<和...)

时间:2016-11-15 01:02:50

标签: ios swift

有人可以解释为什么半开放和关闭范围在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>')

2 个答案:

答案 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有效?
如果您想使用NSRangedescribed 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

the definition