这里有什么问题:实例成员不能用于类型

时间:2015-09-21 10:38:56

标签: ios swift swift2

我有以下代码,我对此错误消息感到困惑:

  

实例成员'mydate'不能用于'TableViewController'类型

代码:

class TableViewController: UITableViewController {    
    let mydate = NSDate()
    let items = [
        (1, 9, 7, "A", mydate),
        (2, 9, 7, "B", mydate),
        (3, 9, 7, "C", mydate),
        (4, 9, 7, "D", mydate)
    ]

当我写下以下内容时,我可以构建它,但我不知道为什么oder代码段不起作用:

class TableViewController: UITableViewController {    
    let mydate = NSDate()
    let items = [
        (1, 9, 7, "A", nil),
        (2, 9, 7, "B", mydate),
        (3, 9, 7, "C", mydate),
        (4, 9, 7, "D", mydate)
    ]

3 个答案:

答案 0 :(得分:41)

这里的问题是你在完全初始化类之前使用self。您可以拥有一个getter,每次访问变量时都会调用它,或者懒惰地计算它。

以下是一些代码:

class TableViewController: UITableViewController {
    let mydate = NSDate()
    var items : [(Int,Int,Int,String,NSDate)] {
        get {
            return [
                (1, 9, 7, "A", mydate),
                (2, 9, 7, "B", mydate),
                (3, 9, 7, "C", mydate),
                (4, 9, 7, "D", mydate)
            ]

        }
    }
}

懒惰计算:

class TableViewController: UITableViewController {
    let mydate = NSDate()
    lazy var items : [(Int,Int,Int,String,NSDate)] =  {

            return [
                (1, 9, 7, "A", self.mydate),
                (2, 9, 7, "B", self.mydate),
                (3, 9, 7, "C", self.mydate),
                (4, 9, 7, "D", self.mydate)
            ]


    }()
}

答案 1 :(得分:3)

您可以使用此代码

var items:Array<(Int, Int, Int, String, NSDate)> {
        get {
            return [
                (1, 9, 7, "A", mydate),
                (2, 9, 7, "B", mydate),
                (3, 9, 7, "C", mydate),
                (4, 9, 7, "D", mydate)
            ]
        }
    }

答案 2 :(得分:-1)

编译器感到困惑,因为它不知道可选NSDate的类型。您可以明确告知其类型。

let items : Array<(Int, Int, Int, String, NSDate?)> = [
    (1, 9, 7, "A", nil),
    (2, 9, 7, "B", mydate),
    (3, 9, 7, "C", mydate),
    (4, 9, 7, "D", mydate)
]

编辑:对于使用实例变量的问题,您可以使用闭包初始化项目。

let items : Array<(Int, Int, Int, String, NSDate?)> = {
    let mydate = NSDate()
    return [
        (1, 9, 7, "A", nil),
        (2, 9, 7, "B", mydate),
        (3, 9, 7, "C", mydate),
        (4, 9, 7, "D", mydate)
    ]
    }()