swift - 在 swift 中让不同的不同子类具有不同的默认值的惯用方式

标签 swift inheritance initialization

我有一个抽象类

class AbstractDevicePrimaryAnnotationView: MKAnnotationView {

    let maskImage:UIImage = UIImage()
    var shape:CALayer

    override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
        // init mine
        self.shape = CALayer()
        // init parents
        super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
        // additional setup     
        self.layer.addSublayer(self.shape)
        self.shape.mask = CALayer()
        self.shape.mask?.contents = self.maskImage.CGImage
    }
}

我希望子类能够为 maskImage 变量设置不同的(真实的)值。但是为我的生活而努力,似乎没有任何效果。

class SubclassAnnoationView: AbstractDevicePrimaryAnnoationView {
    override let maskImage:UIImage! = UIImage(named: "mapValvePrimaryAnnotationMask")!
}

我试过 letvarlazy var。似乎没有任何效果。我收到各种编译器错误。我可以将其设为 Optional,但这似乎是逃避。有没有办法让子类指定自己的常量/静态值?希望是惯用的。

最佳答案

你可以试试

var maskImage: UIImage {
  return UIImage()
}

然后每个子类就做

override var maskImage: UIImage {
   return //whatever image here
}

关于swift - 在 swift 中让不同的不同子类具有不同的默认值的惯用方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30771162/

相关文章:

php - 在继承树中获取 PHP 对象的祖先

c# - 多态,调用父类的子方法

ios - Swift 编译器错误 : Cannot find 'ClassName.h' in scope - Xcode 13

ios - 需要帮助将 mapKit 注释链接到 Swift 中的 CollectionView

Javascript - 经理是一个人而不是经理本身?功能/原型(prototype)继承

java类的初始化顺序,它是如何工作的?

swift - 通过初始化器注入(inject)依赖项(使用 Storyboard)? [ swift ]

c++ - 不稳定的行为

ios - iOS 中的 GMS 标记有时不显示

ios - 使用 EasyMapping (Swift) 解析 Json 数组