5

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.

leavez
  • 2,119
  • 2
  • 27
  • 36
  • 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: https://forums.swift.org/t/clarifying-the-semantics-of-abnormally-terminating-a-storage-access/16244. – Hamish Nov 15 '18 at 18:02

1 Answers1

7

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()
leavez
  • 2,119
  • 2
  • 27
  • 36