NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

SOLVED: Binding implementation in a protocol extension

Forums > Swift

I'm trying to define a Scalable protocol for some of my classes that need to observe a particular scale value on a view controller. The protocol would require a 'scale' variable and a 'bind(to:)' function, like this:

protocol Scalable {
    var scale: CGFloat { get set }
    func bind(to: Observable<CGFloat>)
}

I would like to give a default implementation of the bind(to:) function in a protocol extension of Scalable as follows...

  extension Scalable {
    func bind(to observable: Observable<CGFloat>) {
        observable.valueChanged = { [weak self] newValue in
            self?.scale = newValue ?? 1
        }
    }
}

But I'm getting the following error on [weak self]:

'weak' must not be applied to non-class-bound 'Self'; consider adding a protocol conformance that has a class bound.

I'm not clear on how to interpret this error. Any ideas?

1      

That happens because only object types can be weak -- structs cannot, it doesn't make sense.

To fix that, make your protocol a class-only protocol, like this:

protocol Scalable: AnyObject {
    ...
}

1      

I am using class in these cases and it works great

protocol Scalable: class {

}

1      

Got it now, thanks!

   

Hacking with Swift is sponsored by Fernando Olivares

SPONSORED Would you describe yourself as knowledgeable, but struggling when you have to come up with your own code? Fernando Olivares has a new book containing iOS rules you can immediately apply to your coding habits to see dramatic improvements, while also teaching applied programming fundamentals seen in refactored code from published apps.

Try the book!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.