Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't unwrap Optional.None error in Swift

Tags:

ios

swift

ios8

When the value is passed for UILabel the error appears :

Can't unwrap Optional.None

source code:

@IBOutlet var rowLabel : UILabel

var row: String? {
    didSet {
        // Update the view.
        println(row)
        rowLabel.text = row
    }
}

Also error appears in label in the template for UITable when I appropriate new meaning:

let myCell : Cell =  Cell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell")
myCell.myLabel.text = "(indexPath.row)"
like image 781
Lola Avatar asked Oct 01 '22 15:10

Lola


1 Answers

row is an Optional and it can be nil, i.e. Optional.None, so you need to unwrap it before assignment.

If you don't, I guess the runtime will try to unwrap it anyway, but it will fail with that error whenever a nil value is encountered.

Something like this should be safe

if let r = row {
   rowLabel.text = r    
}

If row is nil, it will never be assigned.

like image 68
Gabriele Petronella Avatar answered Oct 27 '22 09:10

Gabriele Petronella