Partial Function Application with generics

I work with the Observer API ( ObserverSet ), which have the following function:

 public func add<T: AnyObject>(object: T, _ f: T -> Parameters -> Void) -> ObserverSetEntry<Parameters> 

It simply registers object , then calls the instance method f in object when the notification calls

In one of my managers, I need to hide the previous function with one of mine, so that I can force the observer to call the predefined function implemented using the protocol.

Here is what I have done so far:

 @objc protocol Observer : NSObjectProtocol { func observe(param: String) -> Void } func addObserver<T: AnyObject where T: Observer>(observer: T) { let f: T -> String -> Void = observer.dynamicType.observe entries.addObserver(observer, f) } 

Unfortunately, I get the following error: Partial application of generic method is not allowed

I found a possible workaround somewhere on SO that looks like this:

 let f: T -> String -> Void = { (obs: T) in obs.dynamicType.observe(obs) } 

But this line of code makes my Xcode crazy with some Segmentation Fault: 11 when compiling (and Communication interrupted with Playground ..)

Is there any workaround for what I'm trying to do?

+6
source share
1 answer

I have not tested, but you can try:

 @objc protocol Observer : NSObjectProtocol { func observe(param: String) -> Void } func addObserver<T: AnyObject where T: Observer>(observer: T) { let f: T -> String -> Void = { ($0 as AnyObject).observe } entries.addObserver(observer, f) } 

At least this compiles because AnyObject has all the methods from ObjC - including @objc - classes / protocols, like ImplicitlyUnwrappedOptional .

So this compiles:

 let str = NSString(string: "test") (str as AnyObject).observe("foo") 

Of course, this leads to a runtime error, since NSString does not have an observe(_:) method. But in your case T guaranteed to be an Observer , it should work.

+4
source

Source: https://habr.com/ru/post/982069/


All Articles