在Swift中,方法是一种特殊类型的函数,它附着在对象上。
如果给我一个任意函数,我想知道它是否是一个方法。如果是,我想知道它所连接的对象。
类似这样的东西:
func ownerOfFunction(_ f: () -> Void) -> Any? {
return isMethod(f) ? getObject(f) : nil
}
存在类似isMethod()
或getObject()
的东西吗?
func ownerOfFunc<T> (_ parameter: AnyObject,_ type: T.Type) -> Bool {
return parameter is T
}
protocol P1 {}
protocol P2: P1 {}
class C1: NSObject, P2 {
@objc func fuc1() {}
func fuc2() {}
}
let o = C1()
o.responds(to: Selector("fuc1")) // true (Works only Objc selectors)
o.responds(to: Selector("fuc2")) // false
ownerOfFunc(o, P1.self) // true
ownerOfFunc(o, P2.self) // true
ownerOfFunc(o, Int.self) // false