NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

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?


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 {


I am using class in these cases and it works great

protocol Scalable: class {



Got it now, thanks!


Hacking with Swift is sponsored by Paw

SPONSORED Use Paw to build, test and describe web APIs. Paw has a lightning fast native macOS interface to compose requests, collaborate in real-time on API specs, and generate client code for your applications. You can import and export API definitions.

Discover Paw for Mac

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

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

Not logged in

Log in

Link copied to your pasteboard.