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

2.1k Views Asked by At

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.

1

There are 1 best solutions below

0
On

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