将NSObject子类强制转换为非objc协议时Swift崩溃

时间:2016-01-16 08:27:41

标签: swift casting

我花了一些时间搞清楚这一点。这段代码崩溃了:

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 AnimalFourLeggedAnimal
  • 即使您使用软播版,应用程序也会崩溃,即它不是错误的演员,它实际上是Swift运行时的错误。

1 个答案:

答案 0 :(得分:0)

解决方案是将FourLeggedAnimal声明为@objc,或使Animal 继承自NSObject