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      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.