Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

swift

swift2

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)
    ]
like image 275
gurehbgui Avatar asked Sep 21 '15 10:09

gurehbgui


People also ask

Which one of the key Cannot be used with instance variable?

Instance Variable cannot have a Static modifier as it will become a Class level variable. Meaning STATIC is one of the keyword which cannot be used with Instance variable.

What is an instance member?

Unless otherwise specified, a member declared within a class is an instance member. So instanceInteger and instanceMethod are both instance members. The runtime system creates one copy of each instance variable for each instance of a class created by a program.


2 Answers

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


    }()
}
like image 67
avismara Avatar answered Oct 17 '22 20:10

avismara


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)
            ]
        }
    }
like image 26
r4id4 Avatar answered Oct 17 '22 21:10

r4id4