Subscript throws

Hey guys,


I played around with the new error handling and catching and I got stuck with subscripts. Am I doing anything wrong here or is it just a bug/not supported?


extension Array {
    subscript (foo: Int) -> Int {
        return 1
    }
   
    subscript (bar: Int) throws -> Int { // Error
        return 1
    }
}


I'm getting these errors:

Expected declaration

Expected '->' for subscript element type


Thanks

Accepted Answer

First, as a side note, since the external parameter name of the first parameter in methods is implicitly omitted (_), and for subscripts this extends to all parameters, your example has an invalid redeclaration of the subscript (you are in effect only using different local parameter names, which will not make the subscripts unique).

If you want a separate subscript with the external parameter name "bar" you would have to do something like this:


struct Foo {
    subscript(foo: String) -> Void { print("foo: \(foo)") }
    subscript(bar bar: String) -> Void { print("bar: \(bar)") }
}
let f = Foo()
f["Hello world 1"]
f[bar: "Hello world 2"]


Second, as to your actual question: No, it seems like subscripts can't (currently) throw.


Finally, I saw it mentioned on Erica Sadun's blog, that subscripts can't throw, and I could have provided the url, but for some unknown reason this forum software will make this post wait forever for moderation if I do, so I had to remove it (I've noticed that in other posts as well so you'll have to google for it until Apple fixes this forum bug ...).

Thank you!


As a side note of the side note, I removed a lot of code, but your example is way better.

I didn't know about that redeclaration though, thanks.


I'm just going to file a radar then!

Subscript throws
 
 
Q