Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 686
Naftali Beder Avatar asked Feb 09 '15 00:02

Naftali Beder


People also ask

Are optional variables weak in Swift?

No, weak and optional are not the same, but there is some interplay between the two. Optional just means that a variable can be nil , either by assigning nil yourself, or becoming nil through some other means. The weak keyword has to do with memory management.

How do I get rid of optional in Swift?

If my assumption is incorrect, then one quick hack you can quickly do to get rid of the "Optional" in the text is to change your strings to force unwrap item , like so: theYears. text = "\(item!. experience)" .

How do you declare an optional variable in Swift?

Forced Unwrapping If you defined a variable as optional, then to get the value from this variable, you will have to unwrap it. This just means putting an exclamation mark at the end of the variable. Optional("Hello, Swift 4!")


2 Answers

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
like image 158
Dair Avatar answered Oct 05 '22 05:10

Dair


Set its value back to nil like this

myImage = nil
like image 32
Cihan Tek Avatar answered Oct 05 '22 04:10

Cihan Tek