Return an optional value in getter, providing an optional value in setter

class MyClass { private var _image: UIImage var image: UIImage { set { if newValue == nil { _image = UIImage(named: "some_image")! } } get { return _image } } } 

My goal is to guarantee an optional value when handling image

Can I achieve this without an extra feature?

Even if I use didSet / willSet , they are still bound to the UIImage type, and I cannot check nil ...

+6
source share
3 answers

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.

+4
source

You can simply do:

 private var image: UIImage = UIImage(named: "some_image")! 

Thus, the image is initialized by default image, and this image will be used if you do not install another.

 private var _image: UIImage? var image: UIImage? { set { if _image == nil { _image = newValue } } get { return _image } } 
0
source

You can make your _image variable ( _image ) optional, so your public property will not. Use the coalescing operator nil ( ?? ) to determine which return.

 class MyClass { private var _image: UIImage? var image: UIImage { set { _image = newValue } get { return _image ?? UIImage(named: "some_image")! } } } 
0
source

Source: https://habr.com/ru/post/988546/


All Articles