Can't unwrap Optional.None error in swift

戏子无情 提交于 2019-12-21 17:55:02

问题


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)"
    

回答1:


You must use newValue in willSet block, and oldValue in 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"

output:

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



回答2:


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.



来源:https://stackoverflow.com/questions/24035353/cant-unwrap-optional-none-error-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!