Cristian Antonuccio Cristian Antonuccio - 17 days ago 6
Swift Question

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? P.S. Thank you for your answer :)

Answer

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.

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])