Swift protocol compliance: candidate has an inconsistent type

I tried to define a protocol with some property like AnyObject, then in the class that corresponds to the protocol, the property type is SomeClass. However, this led to a compiler error. I had to change the type in the class to AnyObject. How can I use a superclass in a protocol definition and use a subclass as a property type?

Thanks!

protocol TestProtocol {
    var prop: [AnyObject] {get}
}

class Test: TestProtocol {
    var prop = [SomeClass]()    //compiler error
    var prop = [AnyObject]()   //this will work
}
+4
source share
3 answers

An example of a playground for what you can do:

class SomeClass {

}

class Subclass : SomeClass{

}

protocol TestProtocol {
  typealias T : SomeClass
  var prop: [T] {get}
}

class Test: TestProtocol {
  var prop = [Subclass]()

  func test(){
    prop.append(Subclass())
  }
}

let test = Test()
test.test() 
print(test.prop) // prints "[Subclass]\n"
+3
source

An array is an unnecessary complication, so delete it and just think of a simple type. This is not legal:

protocol TestProtocol {
    var prop: AnyObject {get}
}

class SomeClass {}

class Test: TestProtocol {
    var prop : SomeClass = SomeClass() // error
}

, , , , TestProtocol, prop AnyObject - - , AnyObject.

, . , SomeClass , AnyObject. ; SomeClass, AnyObject.

, , :

protocol TestProtocol {
    var prop: AnyObject {get}
}

class SomeClass {}

class Test: TestProtocol {
    var prop : AnyObject = SomeClass() // changing the declared _type_
}

, ; , , , . , , ?

, Swift, , , . , . A typealias . , , . . , , :

protocol TestProtocol {
    typealias T:AnyObject // generic
    var prop: T {get}
}

class SomeClass {}

class Test: TestProtocol {
    var prop : SomeClass = SomeClass() // :)
}

typealias T:AnyObject , T , AnyObject, .

+8

, :

protocol TestProtocol 
{
    typealias ArrayElement: AnyObject
    var prop: [ArrayElement] {get}
}

class Test: TestProtocol 
{
    typealias ArrayElement  = SomeClass
    var prop:[ArrayElement] = []    //No compiler error
}
+1
source

Source: https://habr.com/ru/post/1625428/


All Articles