美文网首页
swift @dynamicCallable和@dynamicM

swift @dynamicCallable和@dynamicM

作者: 迷路的小小 | 来源:发表于2022-03-31 14:52 被阅读0次

动态成员

@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<String, Any>) -> Any
    
    public init(_ closure: @escaping (KeyValuePairs<String, Any>) -> Any) {
        self.closure = closure
    }
    @discardableResult
    public func dynamicallyCall(withKeywordArguments args: KeyValuePairs<String, Any>) -> Any {
        return closure(args)
    }
}

使用

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

相关文章

网友评论

      本文标题:swift @dynamicCallable和@dynamicM

      本文链接:https://www.haomeiwen.com/subject/tqknjrtx.html