Cannot override mutable property 'a1' of type 'A' with covariant type 'B'

Overview:

I have mentioned below a simplified example that causes the error Cannot override mutable property 'a1' of type 'A' with covariant type 'B'

Real Problem:

I have an iOS project in which when similar code is compiled on Xcode (for the simulator)

  • Sometimes it compiles ok (not sure if it was the cache)
  • Sometimes I get Command CompileSwift failed with a nonzero exit code
  • Sometimes I get Cannot override mutable property 'a1' of type 'A' with covariant type 'B'

Sorry the above explanation is very vague, when I created a new project with the below classes, I consistently get Cannot override mutable property 'a1' of type 'A' with covariant type 'B'

Note:

  • In my real world project when I change the overriding type to be the same, the code consistently compiles fine.
  • The overriding property was a subclass of UITextField (Based on the above pasted forum link, there was some pointers about how Objective-C might not be as strict as Swift, so I am not sure if it was because UITextField was written in Objective-C)

On the surface it seemed like valid code, but based on In a sub-class, is it possible to override a property of the super-class and constrain to a sub-type of the original property?, I understand that I shouldn't be overriding this way because of the example explained. (table view / scroll view delegate example).

Questions:

  1. Is the inconsistency in compilation error / success something that has been noticed by others too or is this a problem with my project ?
  2. Let me know if there is a way to find more from the non-zero error code.

Code:

class A {}
class B : A {}

class Car {
    private (set) var a1 = A()
}

class SpecialCar : Car {
    override var a1: B {
        return B()
    }
}

Change override var a1: B { ... } to override var a1: A { ... }

Also, I suggest you to read https://www.mikeash.com/pyblog/friday-qa-2015-11-20-covariance-and-contravariance.html.

1 Like

Thanks @suyashsrijan on the surface my code seemed reasonable until I read the post on Swift Forums about a similar thread. I will read the link you posted.

I am just wondering what could be the inconsistency in compilation error and sometimes even compiled ok, not sure I am made a blunder or if it was some cache somewhere.

Cache issues are usually related to an error message not going away. In your case, CompileSwift failed tells me it might very well be a compiler crash. Try looking for a stack dump in Xcode's report navigator when the build fails. I suggest not just compiling, but running the app as well to be sure a build succeeded.

1 Like
Terms of Service

Privacy Policy

Cookie Policy