[英]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. 基本上是让
UIImage
自动指向nil
简写。
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; Optional
是Swift中的enum
类型; 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)
. 通过将图像分配给
Optional<UIImage>
,您已隐式指定.Some(image)
。 To clear it, you can use .None
. 要清除它,您可以使用
.None
。 But since Optional
also conforms to NilLiteralConvertible
, you can use the simpler and clearer nil
. 但由于
Optional
也符合NilLiteralConvertible
,因此您可以使用更简单,更清晰的nil
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.