swift2 这里有什么问题:执行严修成员不能用于类型[duplicate]

8wigbo56  于 2022-11-06  发布在  Swift
关注(0)|答案(3)|浏览(137)

此问题在此处已有答案

How to initialize properties that depend on each other(4个答案)
Instance member cannot be used on type(8个答案)
七年前就关门了。
我有下面的代码,我对这个错误消息感到困惑:
执行严修成员'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)
    ]
ruyhziif

ruyhziif1#

这里的问题是你在类完全初始化之前就使用了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)
            ]

    }()
}
0aydgbwb

0aydgbwb2#

您可以使用此代码

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)
            ]
        }
    }
zzwlnbp8

zzwlnbp83#

编译器会感到困惑,因为它不知道可选的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)
    ]
    }()

相关问题