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.
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.
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()
© 2022 - 2024 — McMap. All rights reserved.