How to declare "throws" for `subscript(dynamicMember:)`in @dynamicMemberLookup in swift?
Asked Answered
S

1

7

When using @dynamicMemberLookup in swift, subscript cannot declare a "throws".

subscript(dynamicMember member: String) -> Any

This is OK.

subscript(dynamicMember member: String) throws -> Any

This will give a compile error.

Streamway answered 15/11, 2018 at 17:53 Comment(1)
Swift doesn't yet support throwing subscripts or computed properties in general. Here's a relevant thread discussing what the semantics of such declarations would be: forums.swift.org/t/….Rheumy
S
8

Using throws in subscript is not supported by the language right now. However you can use some tricks to avoid that, meanwhile, keep the feature of throws:

public subscript(dynamicMember member: String) -> () throws -> Any {
    return { try REAL_FUNCTION_THAT_THROWS()  }
}

Just declare the subscription return an block, then add a () behind the function to execute the real function. So you could code like this:

@dynamicMemberLookup
class A {
    public subscript(dynamicMember member: String) -> () throws -> Any {
         return { try REAL_FUNCTION_THAT_THROWS()  }
    }
}

let a = A()
let value = try? a.doWhatYouWant()
let value2 = try? a.anotherMethod()
Streamway answered 15/11, 2018 at 18:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.