What's wrong here: Instance member cannot be used on type [duplicate]
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) ] }()}
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) ] }()