gpt4 book ai didi

ios - Swift 字符串的范围运算符(..< 和 ...)

转载 作者:搜寻专家 更新时间:2023-11-01 07:18:20 24 4
gpt4 key购买 nike

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

最佳答案

要完成您想要做的事情,请不要调用 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"

关于ios - Swift 字符串的范围运算符(..< 和 ...),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40600407/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com