简体   繁体   中英

Type does not conform to protocol - typealias to another protocol

I'm facing an anoying problem and I was hopping that you guys could help me with that.

I have two protocols and one class:

protocol Prot1: AnyObject {

}

protocol Prot2 {
    associatedtype T: AnyObject
}

class TheClass: Prot2 {
    typealias T = Prot1
}

This causes the compiler to say:

  • Type 'TheClass' does not conform to protocol 'Prot2'.

In the navigation it shows more details:

  • Protocol requires nested type 'T'
  • Possibly intended match 'T' (aka 'Prot1') does not conform to 'AnyObject'

I realy need the associated type to be of the AnyObject type. This is why I need help.

Does anyone know how to solve this?

Thank you very much.

OBS: I'm using swift 2.3

To show the nature of what you can do here, I will simplify the example slightly. This is legal:

protocol Prot {
    associatedtype T: AnyObject
}
class TheClass: Prot {
    typealias T = AnyObject // fine
}

This is also legal:

protocol Prot {
    associatedtype T: AnyObject
}

class TheClass: Prot {
    typealias T = NSObject // fine
}

That's because NSObject is a type that is an adopter of AnyObject.

But this (what you're trying to do) is not legal:

protocol Prot {
    associatedtype T: AnyObject
}

protocol SecondProt : AnyObject {

}

class TheClass: Prot {
    typealias T = SecondProt // error
}

The reason is that SecondProt is another protocol that adopts AnyObject. That is not something that can go in the typealias T slot.

This has nothing to do with the special nature of AnyObject. We can get the same error without mentioning AnyObject anywhere:

protocol P {}

protocol Prot {
    associatedtype T: P
}

protocol SecondProt : P {

}

class TheClass: Prot {
    typealias T = SecondProt // error
}

Again, if we supply a type that adopts P, we're fine:

protocol P {}

protocol Prot {
    associatedtype T: P
}

struct S : P {

}

class TheClass: Prot {
    typealias T = S // fine
}

Change Anyobject to Any is ok, or delete Anyobject. Anyobject is class type. Type Casting for Any and AnyObject

This snippet compiles. But I am not sure if it's what you're looking for...

protocol Prot1: AnyObject 
{

}

protocol Prot2 
{
    associatedtype T: AnyObject
}

class TheClass: Prot2 
{
    typealias U = Prot1
    typealias T = AnyObject
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM