Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't unwrap 'Optional.None'

Tags:

ios

swift

When confronting the error fatal error:

Can't unwrap Optional.None

It is not that easy to trace this. What causes this error?

Code:

import UIKit

class WelcomeViewController: UIViewController {
    let cornerRad:CGFloat = 10.0
    @IBOutlet var label:UILabel
    @IBOutlet var lvl1:UIButton
    @IBOutlet var lvl2:UIButton
    @IBOutlet var lvl3:UIButton
    init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        lvl1.layer.cornerRadius = cornerRad
        lvl2.layer.cornerRadius = cornerRad
        lvl3.layer.cornerRadius = cornerRad
    }
}
like image 381
Tony Avatar asked Jun 03 '14 02:06

Tony


2 Answers

You get this error, because you try to access a optional variable, which has no value. Example:

// This String is an optional, which is created as nil.
var optional: String?

var myString = optional! // Error. Optional.None

optional = "Value"
if optional {
    var myString = optional! // Safe to unwrap.
}

You can read more about optionals in the official Swift language guide.

like image 113
Leandros Avatar answered Sep 22 '22 12:09

Leandros


When you see this error this is due to an object such as an unlinked IBOutlet being accessed. The reason it says unwrap is because when accessing an optional object most objects are wrapped in such a way to allow the value of nil and when accessing an optional object you are "unwrapping" the object to access its value an this error denotes there was no value assigned to the variable.

For example in this code

var str:String? = nil
var empty = str!.isEmpty

The str variable is declared and the ? denotes that it can be null hence making it an OPTIONAL variable and as you can see it is set to nil. Then it creates a inferred boolean variable empty and sets it to str!.isEmpty which the ! denotes unwrap and since the value is nil you will see the

Can't unwrap Optional.None error
like image 29
Tony Avatar answered Sep 20 '22 12:09

Tony