gpt4 book ai didi

swift - "subscript"的使用不明确

转载 作者:可可西里 更新时间:2023-11-01 01:03:22 33 4
gpt4 key购买 nike

我在尝试使用下标访问范围的第 n 个元素时遇到问题。代码 super 简单:

var range = 0..<9
var itemInRange = range[n] // n is some Int where 0 <= n < 9

第二行提示错误 Ambiguous use of "subscript",我的意思是 Xcode 不清楚变量 range 的类型是什么, 所以它无法知道要使用 subscript 的哪个实现。我试图通过用

显式定义 range 的类型来解决这个问题
var range: Range<Int> = 0..<9

var firstInRange = (range as Range<Int>)[0]

但是这些都没有解决问题。有没有办法让 Xcode 消除对 subscript 的调用的歧义?

最佳答案

您可以创建一个包含范围的数组,然后从该数组中选取一个元素。

var range = [Int](0..<9)
var itemInRange = range[1]

来自苹果文档

A collection of consecutive discrete index values.

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.

Axiom: for any Range r, r[i] == i.

Therefore, if Element has a maximal value, it can serve as an endIndex, but can never be contained in a Range.

It also follows from the axiom above that (-99..<100)[0] == 0. To prevent confusion (because some expect the result to be -99), in a context where Element is known to be an integer type, subscripting with Element is a compile-time error:

// error: could not find an overload for 'subscript'...

print(Range(start: -99, end: 100)[0])

https://developer.apple.com/library/prerelease/mac/documentation/Swift/Reference/Swift_Range_Structure/index.html

关于swift - "subscript"的使用不明确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33489063/

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