Ios Swift字符串上的范围运算符(..<;和…)

Ios Swift字符串上的范围运算符(..<;和…),ios,swift,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

有人能解释一下为什么在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”
让start=hello.index(hello.startIndex,offsetBy:1)
让end=hello.index(hello.startIndex,offsetBy:4)
让范围=开始..

  • 为什么
    let range=start..要执行您试图执行的操作,请不要调用
    子字符串(使用:)
    。直接下标:

    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"
    
    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>')
    
    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
    
    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"