我花了一些时间搞清楚这一点。这段代码崩溃了:
public protocol FourLeggedAnimal: AnyObject {
}
public class Animal: NSObject {
}
public class Dog: Animal, FourLeggedAnimal {
}
public class AnimalProperty<Kind: Animal>: NSObject {
let animal: Kind
public init(animal: Kind) {
self.animal = animal
}
}
public class FourLeggedAnimalProperty<Kind: Animal>: AnimalProperty<Kind>, NSTextFieldDelegate {
public override init(animal: Kind) {
/// Since we cannot express in Swift that the Kind should be an Animal
/// subclass confirming to a particular protocol, we use a force-cast
/// which is not a pretty solution, but there aren't any options.
/// And this crashes.
let fourLeggedAnimal = animal as! FourLeggedAnimal
print(fourLeggedAnimal)
super.init(animal: animal)
}
}
let dog = Dog()
let property = FourLeggedAnimalProperty(animal: dog)
当您尝试将狗插入初始化程序中的getGenericPattern()
协议时,代码会在Swift的库FourLeggedAnimal
函数中崩溃。
注意:
<Kind: Animal, FourLeggedAnimal>
,但是,当您这样做时,您无法使用init(animal:)
调用Dog
初始化程序,即使它& #39; s Animal
和FourLeggedAnimal
。答案 0 :(得分:0)
解决方案是将FourLeggedAnimal
声明为@objc
,或使Animal
不继承自NSObject
。