简体   繁体   中英

Clear an optional variable in Swift

If I declare an empty image:

var myImage: UIImage?

and then give it a value:

myImage = UIImage(named: "drawing.png")

how can I later remove that value, returning it to its original empty state?

var myImage: UIImage?

Is basically short hand for making a UIImage point to nil automatically.

So to reset it back to the original value say:

myImage = nil

将其值设置为nil,就像这样

myImage = nil

只需为它指定nil

myImage = nil

Optional is an enum type in Swift; it has two cases:

enum Optional<T> : NilLiteralConvertible {
    case None
    case Some(T)
    ...
}

By assigning an image to your Optional<UIImage> , you have implicitly specified .Some(image) . To clear it, you can use .None . But since Optional also conforms to NilLiteralConvertible , you can use the simpler and clearer nil .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM