gpt4 book ai didi

swift 3;范围 'Out of bounds'

转载 作者:搜寻专家 更新时间:2023-10-31 08:20:11 25 4
gpt4 key购买 nike

我刚刚将 Xcode 更新到 8.0 beta 2 和 swift 3.0。从 swift 2.3 更新后,我遇到了很多错误。

我有一个字符串扩展,它将“self”字符串中的范围转换为 NSRange:

extension String {

func NSRangeFromRange(_ range : Range<String.Index>) -> NSRange {

let utf16view = self.utf16
let from = String.UTF16View.Index(range.lowerBound, within: utf16view)
let to = String.UTF16View.Index(range.upperBound, within: utf16view)

print("to: \(to) from: \(from)")
print(self.characters.count)

return NSMakeRange(utf16view.startIndex.distance(to: from), from.distance(to: to))
// return NSMakeRange(0, 0) // <-- removes exception
}
}

执行 NSMakeRange 时出现错误:

Terminating app due to uncaught exception 'NSRangeException', reason: 'NSMutableRLEArray objectAtIndex:effectiveRange:: Out of bounds'

当我打印 to- 和 from-index 时,我得到:

to: Index(_offset: 194) from: Index(_offset: 181)

字符串的字符数是 210,这似乎是正确的。

所以,我不明白为什么它告诉我索引超出范围,当它们小于总数时。

在我更新到 swift 3 之前,这条线运行良好。当时它看起来像这样:

return NSMakeRange(utf16view.startIndex.distanceTo(from), from.distanceTo(to))

自动转换器没有将语法从 swift 2.3 更新到 3.0,我自己做了。

有什么线索吗?

最佳答案

在 Swift 3 中,“Collections move their index”,参见 A New Model for Collections and Indices关于 Swift 演进。

在 Swift 2.2 中,advancedBy()distanceTo()方法是在索引上调用:

let u16 = "12345".utf16
let i1 = u16.startIndex.advancedBy(1)
let i2 = u16.startIndex.advancedBy(3)
let d = i1.distanceTo(i2)
print(d) // 2

这个方法在 Swift 3 中仍然存在,但给出了意想不到的结果,至少在字符集合上是这样:

let u16 = "12345".utf16
let i1 = u16.startIndex.advanced(by: 1)
let i2 = u16.startIndex.advanced(by: 3)
let d = i1.distance(to: i2)
print(d) // -2

正确的方法是使用 index()distance()方法 集合本身:

let u16 = "12345".utf16
let i1 = u16.index(u16.startIndex, offsetBy: 1)
let i2 = u16.index(u16.startIndex, offsetBy: 3)
let d = u16.distance(from: i1, to: i2)
print(d) // 2

应用于您的问题,这就是您可以转换 Range<String.Index>到对应的NSRange在 swift 3(从 https://stackoverflow.com/a/30404532/1187415 复制):

extension String {
func nsRange(from range: Range<String.Index>) -> NSRange {
let utf16view = self.utf16
let from = range.lowerBound.samePosition(in: utf16view)
let to = range.upperBound.samePosition(in: utf16view)
return NSMakeRange(utf16view.distance(from: utf16view.startIndex, to: from),
utf16view.distance(from: from, to: to))
}
}

为了完整起见,这是相反的转换

extension String {
func range(from nsRange: NSRange) -> Range<String.Index>? {
guard
let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex),
let to16 = utf16.index(from16, offsetBy: nsRange.length, limitedBy: utf16.endIndex),
let from = String.Index(from16, within: self),
let to = String.Index(to16, within: self)
else { return nil }
return from ..< to
}
}

关于 swift 3;范围 'Out of bounds',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38227245/

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