Overriding properties in swift

Interestingly this works just fine in pure Swift classes. For example, this works as expected:

public class FooButton {
    public var weight: Double = 1.0
}

public class BarButton: FooButton {
    override public var weight: Double = 2.0
}

The reason it does not work for you is because you are working with Objective-C classes: since UIButton is an Objective-C class, all its subclasses will be too. Because of that, the rules seem to be a bit different.

Xcode 6.3 is actually a bit more informative. It shows the following two errors:

Getter for “weight” overrides Objective-C method “weight” from superclass “FooButton”
Setter for “weight” overrides Objective-C method “setWeight:” from superclass “Foobutton”

Since the following does work …

public class BarButton: FooButton {
    override public var weight: Double {
        get {
            return 2.0
        }
        set {
            // Do Nothing
        }
    }
}

… my guess is that these methods are simply not synthesized correctly.

I wonder if this is a compiler bug. Or a shortcoming. Because I think it could handle the case.

Maybe the Swift designers thought that in case of overriding weight you could also simply set it to a different value in your initializer. Hm.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)