简体   繁体   English

如何快速在@dynamicMemberLookup中为下标(dynamicMember :)声明“抛出”?

[英]How to declare “throws” for `subscript(dynamicMember:)`in @dynamicMemberLookup in swift?

When using @dynamicMemberLookup in swift, subscript cannot declare a "throws". 快速使用@dynamicMemberLookup时, subscript无法声明“抛出”。

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. 该语言目前不支持使用subscript throws However you can use some tricks to avoid that, meanwhile, keep the feature of throws : 但是,您可以使用一些技巧来避免这种情况,同时保留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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM