gpt4 book ai didi

Swift Range 表现得像 NSRange 并且不包括 endIndex

转载 作者:行者123 更新时间:2023-11-28 08:49:37 24 4
gpt4 key购买 nike

我遇到了一些奇怪的 Range 行为,现在我质疑我认为我知道的关于 Swift 中的 Range 的一切。

let range = Range<Int>(start: 0, end: 2)
print(range.count) // Prints 2

由于 Range 使用 startend 而不是 locationlength NSRange 使用我希望上面的范围计数为 3。它几乎看起来像被视为 NSRange 因为如果计数为 2 是有意义的您的 location = 0length = 2

let array = ["A", "B", "C", "D"]
let slice = array[range]

我希望 slice 包含 ABC 因为范围的结束索引是 2,但 slice 实际上包含 AB ,它确实对应于 range.count == 2,但不会相加,因为范围的 endIndex == 2 应该包括 C.

我在这里错过了什么?

我使用的是 Xcode 7.2 版本的 Swift,而不是任何开源版本。

最佳答案

范围对象 Range<T>在 Swift 中,默认情况下,呈现为半开区间 [start,end) ,即 start..<end (参见 HalfOpenInterval IntervalType)。

如果你打印你的 range 就可以看到这个变量

let range = Range<Int>(start: 0, end: 2)
print(range) // 0..<2

此外,正如 Leo Dabus 在下面指出的(谢谢!),您可以简化 Range<Int> 的声明。通过使用半开范围运算符 ..<直接:

let range = 0..<2
print(range) // 0..<2 (naturally)

同样,你可以声明Range<Int>使用封闭范围运算符的范围 ...

let range = 0...1
print(range) // 0..<2

我们看到,有趣的是(在问题的上下文中),这再次验证了范围的默认表示是通过半开运算符。


半开间隔是 Range 的默认值在 language reference for range 的文本中有些含蓄地写着:

Like other collections, a range containing one element has an endIndex that is the successor of its startIndex; and an empty range has startIndex == endIndex.

Range然而,符合 CollectionType协议(protocol)。在 the language reference to the latter , 它清楚地表明 startIndexendIndex定义半开区间:

The sequence view of the elements is identical to the collection view. In other words, the following code binds the same series of values to x as does for x in self {}:

for i in startIndex..<endIndex {
let x = self[i]
}

把它包起来; Range被定义为半开间隔 ( startIndex ..< endIndex ),即使在文档中很难找到它。


另见

Swift includes two range operators, which are shortcuts for expressing a range of values.

...

The closed range operator (a...b) defines a range that runs from a to b, and includes the values a and b. The value of a must not be greater than b.

...

The half-open range operator (a..< b) defines a range that runs from a to b, but does not include b. It is said to be half-open because it contains its first value, but not its final value.

关于Swift Range 表现得像 NSRange 并且不包括 endIndex,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34539271/

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