UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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?

4      

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 {
    ...
}

4      

I am using class in these cases and it works great

protocol Scalable: class {

}

4      

Got it now, thanks!

3      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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.