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)
]
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.
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.
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)
]
}()
}
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)
]
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With