这是来自Swift游乐场;我想在一个数组中收集我的'Task'类实例,这样每个任务的属性都可以在tableview中使用。我正在搜索文档,但我没有看到如何正确初始化和访问数组中的类的讨论。
最后一行代码给出了一个错误,该错误读取 AnyObject没有名为deadline 的成员。无论我使用的是AnyObjects的Swift数组还是空的NSMutableArray都是一样的。我尝试了各种方法将其作为Integer进行投射,但它坚持这个错误。我是否以错误的方式存储然后访问数据?我是javascript-brained,有时语法的相似性会让我产生妄想。
import UIKit
let todays_date = NSDate() // now
let cal = NSCalendar.currentCalendar()
let day_number = cal.ordinalityOfUnit(.CalendarUnitDay, inUnit: .CalendarUnitYear, forDate: todays_date)
var tasks = [] as NSMutableArray
class Task {
var title: String
var interval: Int
var dateActivated: Int
var deadline: Int
var flag_count: Int = 0
var isActivated: Bool = false
init(title: String, dateActivated: Int, interval: Int) {
//initialized by selecting new
self.title = title
self.dateActivated = dateActivated
self.interval = interval
//calculated
self.deadline = dateActivated + interval
}
}
var task1 = Task(title: "Laundry", dateActivated: day_number, interval: 7)
var task2 = Task(title: "Dishes", dateActivated: day_number, interval: 7)
task1.deadline
task2.flag_count
tasks.addObject(task1)
tasks.addObject(task2)
tasks[0].deadline //AnyObject does not have member named deadline
答案 0 :(得分:0)
这里不需要使用基础数组,只需将数组声明为[Task]
(在声明Task
类之后):
var tasks = [Task]()
然后使用append
代替addObject
:
tasks.append(task1)
tasks.append(task2)
tasks[0].deadline // 83