Idiomatic way to have different different subclasses in swift have different default values

41 views Asked by At

I have an abstract class

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
    }
}

I want subclasses to be able to have different (and real) values for the maskImage var. But try for the life of me, nothing seems to work.

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

I've tried let, var, lazy var. Nothing seems to work. I get a variety of compiler errors. I could make it an Optional, but that seems like a cop out. Isn't there a way to let subclasses designate their own constant/static values? Hopefully one that's idiomatic.

1

There are 1 answers

1
ad121 On

You could try

var maskImage: UIImage {
  return UIImage()
}

Then each subclass just do

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