Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return non optional value in getter, while allowing 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 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...

like image 582
jovanMeshkov Avatar asked Jun 05 '15 02:06

jovanMeshkov


1 Answers

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.

like image 148
Mick MacCallum Avatar answered Sep 21 '22 00:09

Mick MacCallum