It looks like you want to use the implicitly expanded option. Since your getter is just a wrapper for optional UIImage, you know that your getter will always return nil (and since image implicitly expanded, it will be treated as such), but it will also allow your setter to accept nil. Maybe something like this.
class MyClass { private var _image: UIImage // ... var image: UIImage! { get { return _image } set { if let newValue = newValue { _image = newValue } else { _image = UIImage(named: "some_image")! } } } }
Where
image = nil
will set _image your default and
image = UIImage(named: "something_that_exists")!
will assign a new _image image. Note that this also allows you to assign a variable from UIImage(named:) without forcing an optional UIImage(named:) . If the UIImage initializer fails because it cannot find the image, it will evaluate to nil and still cause _image to be assigned _image your default image.
source share