Unable to unzip option.

When a value is passed for UILabel, an error appears:   

Can't unwrap Optional.None

source:   

    @IBOutlet var rowLabel: UILabel
var row: String? { didSet { // Update the view. println (row) rowLabel.text = row } }
An error also appears in the shortcut in the template for UITable when I approach the new value:   
    let myCell: Cell = Cell (style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell")
            myCell.myLabel.text = "(indexPath.row)"
    
+4
source share
2 answers

You should use newValue in the willSet block, and oldValue in the didSet block

Example:

class foo {
    var row: String? {
    willSet {
        println("will set value:")
        println(newValue)
    }

    didSet {
        println("did change value:")
        println(oldValue)
    }
    }
}

var bar = foo()

println("First time setter called")
bar.row = "First value"
println("Second time setter called")
bar.row = "Second value"

conclusion:

First time setter called
will set value:
First value
did change value:
nil
Second time setter called
will set value:
Second value
did change value:
First value
+1

row Optional nil, .. Optional.None, .

, , , , nil.

-

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

row - nil, .

+2

Source: https://habr.com/ru/post/1543192/


All Articles