简体   繁体   English

无法快速扩展下标

[英]Can't Subscript from swift extension

This is the problem: 这就是问题:

typealias Byte = UInt8

protocol ByteProtocol {}
extension UInt8: ByteProtocol {}

extension Array where Element: ByteProtocol  {

    subscript (index: Int) -> UInt8 {
        return self[Int(index % self.count)]
    }

}

This gives me Overflow even if it is mathematically impossible: 即使在数学上不可能,这也会给我带来溢出:

var p: [Byte] = [Byte]()
p.append(15)
print(p[10])

So what is the mistake here? 那么这是什么错误呢? PS Thank you for your answer :) PS谢谢您的回答:)

You can't overload subscripts this way. 您不能以这种方式重载下标。 Even if you could, you'd be creating an infinite loop in your implementation. 即使可以,您仍将在实现中创建一个无限循环。 Your implementation also would be illegal, since it returns something other than Element . 您的实现也将是非法的,因为它返回的不是Element

What you mean is something like this: 您的意思是这样的:

extension Array where Element: ByteProtocol  {

    subscript (wrapping index: Int) -> Element {
        return self[Int(index % self.count)]
    }
}

var p: [Byte] = [Byte]()
p.append(15)
print(p[wrapping: 10])

It doesn't give you an "overflow". 它不会给您“溢出”。 It gives you an out-of-range error. 它给您超出范围的错误。 There is no element index 10 in an array with only 1 element. 只有1个元素的数组中没有元素索引10。 The crash occurs before your subscript implementation is ever called (as you could easily discover by breakpointing it). 崩溃发生在调用subscript实现之前(因为您可以通过断点轻松发现它)。 You cannot magically change the meaning of an existing subscript implementation in the way you are hoping to. 您无法以您希望的方式神奇地更改现有subscript实现的含义。

The default implementation of subscript is called, not yours. 下标的默认实现称为,而不是您的。 Hence, it's trying to actually access the 10th element, which doesn't exist. 因此,它试图实际访问第十个元素,该元素不存在。

You can't override the behaviour of a struct like Array using an extension. 您不能使用扩展覆盖Array之类的结构的行为。 They're not polymorphic. 它们不是多态的。 You can, however, add a new definition of a subscript, as rob showed. 但是,您可以添加新的下标定义,如rob所示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM