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 non-optional value when image
is accessed
Can i achieve this without additional function?
Even if i use didSet
/willSet
they are still bound to that UIImage
type and i can't check for nil
...
Sounds like you want to use an implicitly unwrapped optional. Since your getter is just a wrapper for a non optional UIImage you know that your getter will always produce a non nil value (and since image
is implicitly unwrapped, it will be treated as such), but this will also allow your setter to accept nil values. Perhaps 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 assign _image
your default value, and
image = UIImage(named: "something_that_exists")!
will assign the new image to _image
. Note that this also allows you to assign to the variable from UIImage(named:)
without forcibly unwrapping the optional. If UIImage's initializer fails because it can't find the image, it will evaluate to nil and still cause _image
to be assigned your default image.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With