swift @dynamicCallable和@dynamicMemberLookup的使用

动态成员

@dynamicMemberLookup
public class Service {
    var factories = [String: Factory]()
    
    public subscript(dynamicMember member: String) -> Factory! {
        get {
          factories[member]
        }
        set {
           factories[member] = newValue
        }
    }
}

动态方法

@dynamicCallable
public struct Factory {
    public let closure: (KeyValuePairs) -> Any
    
    public init(_ closure: @escaping (KeyValuePairs) -> Any) {
        self.closure = closure
    }
    @discardableResult
    public func dynamicallyCall(withKeywordArguments args: KeyValuePairs) -> Any {
        return closure(args)
    }
}

使用

let service = Service()
service.getNum = Factory(closure: { (params) -> Any in
  return 1
})
service.getNum(1, num: 3) // 1

你可能感兴趣的:(swift @dynamicCallable和@dynamicMemberLookup的使用)