无法解开swift中的Optional.None错误 [英] Can't unwrap Optional.None error in swift

查看:115
本文介绍了无法解开swift中的Optional.None错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当UILabel传递该值时,出现错误:

When the value is passed for UILabel the error appears :

Can't unwrap Optional.None

源代码:


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


模板中的标签中也出现错误当我适用新的含义时为UITable:

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

推荐答案

你必须在willSet中使用newValue阻止和didSet块中的oldValue

You must use newValue in willSet block, and oldValue in didSet block

示例:

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

这篇关于无法解开swift中的Optional.None错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆