What's wrong here: Instance member cannot be used on type [duplicate]

旧巷老猫 提交于 2019-12-17 16:25:23

问题


I have the following code and I'm confused about this error message:

Instance member 'mydate' cannot be used on type 'TableViewController'

Code:

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

When I write the following, I can build it but I don't know why the oder snippet is not working:

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

回答1:


The problem here is that you are using self before the class is fully initialised. You can either have a getter which will be called every time you access the variable or compute it lazily.

Here is some code:

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

        }
    }
}

Lazy computation:

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


    }()
}



回答2:


You can use this code

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



回答3:


The compiler gets confused because it doesn't know the type of the optional NSDate. You can let it know explicitly about the type.

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

Edit: For the problem with using instance variable, you could initialise your items with a closure.

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


来源:https://stackoverflow.com/questions/32693150/whats-wrong-here-instance-member-cannot-be-used-on-type

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