当为UILabel传递值时,会出现错误:
Can't unwrap Optional.None
源代码:
@IBOutlet var rowLabel : UILabel当我适用新的含义时,UITable模板中的标签中也会出现错误:
var row: String? { didSet { // Update the view. println(row) rowLabel.text = row } }
let myCell : Cell = Cell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell") myCell.myLabel.text = "(indexPath.row)"
答案 0 :(得分:2)
row
是Optional
,可以是nil
,即Optional.None
,因此您需要在分配前将其解包。
如果你不这样做,我想运行时会尝试解开它,但只要遇到nil
值,它就会失败并显示错误。
这样的事情应该是安全的
if let r = row {
rowLabel.text = r
}
如果row
为nil
,则永远不会分配。{/ p>
答案 1 :(得分:1)
你必须在willSet块中使用newValue,在didSet块中使用oldValue
示例:
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"
输出:
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