2015-11-02 63 views
2

我遇到了一个问题,试图使用下标访问Range的第n个元素。该代码是超级简单:模糊使用“下标”

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

第二行抱怨与错误Ambiguous use of "subscript",我采取意味着Xcode中不明确的变量range的类型是什么,所以它无法知道哪一个实现subscript使用。我试图用

var range: Range<Int> = 0..<9 

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

但是这些都解决了这个问题明确界定range类型解决这一问题。有没有办法让Xcode消除对subscript的呼叫?

回答

2

您可以使用范围创建一个数组,然后从数组中选取一个元素。

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

+0

您的推荐代码工作得很好,但我完全被你支持张贴的公理混淆。你能告诉我这个来源吗?对于我来说,一个范围中不是从零开始的第零个元素是零。 – Ziewvater

+0

对不起。我应该包括这个链接。 https://developer.apple.com/library/prerelease/mac/documentation/Swift/Reference/Swift_Range_Structure/index.html – Moriya

+0

所以根本就不可能在'Range'上使用下标吗?考虑到苹果给出的推理,我想这是有道理的,但它似乎是如此的人为设计,并且立即可以被证明是没有道理的。他们提出的公理有没有一些奇怪的计算机科学理论? – Ziewvater