I've read many articles about using Self
inside protocol
but I am still confused how to achieve some behaviour.
Code
protocol Bindable {
@discardableResult
func bind(_ target: inout Self) -> Self
}
extension Bindable {
@discardableResult
func bind(_ target: inout Self) -> Self {
target = self
return self
}
}
Attempt
extension NSView: Bindable {} // ERROR
Error
Complain I am using Self
so it can be any subclass of NSView
Protocol 'Bindable' requirement 'bind' cannot be satisfied by a non-final class ('NSView') because it uses 'Self' in a non-parameter, non-result type position
Question:
How should I implement protocol Bindable
so it uses current variable type?
or
How to apply protocol to any type to make function require type of variable itself?
Tests
Everything works ... except application to NSView
class MyView: NSView {}
let view: NSView
let myTarget: MyView
NSView().bind(&view) // OK
(MyView() as NSView).bind(&view) // OK
MyView().bind(&myTarget) // OK
NSView().bind(&myTarget) // Error = OK (expected)
MyView().bind(&view) // Error = OK (expected)
It seems compiler understands and does exactly what I want to achieve. Clearly recognises type of variable and allows only its type as a parameter. It is strange that auto-completion and semantic is correct but it's not compilable.