2016-11-15 60 views
1

有人可以解釋爲什麼半開和關閉範圍不再在Swift 3中的字符串上工作相同?範圍運算符(.. <和...)在Swift字符串

此代碼:

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
  • 爲什麼let range = start..<end工作?

NSRange是你需要的,如果你想使用substring(with:)described here)。

這裏是Rangethe definition

在可比類型的半開區間,從下限到, 但不包括上限。

要創建一個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 
  • 如何轉換ClosedRangeRange

Converting between half-open and closed ranges

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"