动态成员
@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
网友评论