我有一个数据控制器,它应该接收数据,然后将其放入UITableViewDataSource。我似乎无法访问init中的变量。
如果我取消注释init中的var sections声明,那么我得到一个错误,“类型DataController1的值没有成员节”
有人能告诉我我错过了什么吗?
相关的代码行如下:
class DataController1: NSObject, DataController {
struct Section {
let type: SectionTypeEnum
let rows: [Any]
}
let contactData: ContactData
var section1: [Section1]!
var section2: [Section2]!
var section3: [Section3]!
// var sections = [Section]!
init(contactData: ContactData) {
self.contactData = contactData
self.section1 = self.contactData.list1
self.section2 = self.contactData.list2
self.section3 = self.contactData.list3
// var sections: [Section] = [
// Section(type: .section1, rows: section1),
// Section(type: .section2, rows: section2),
// Section(type: .section3, rows: section3),
//]
}
var sections: [Section] = [
Section(type: .section1, rows: section1),
//Cannot use instance member 'section1' within property initializer; property initializers run before 'self' is available
// current error
Section(type: .section2, rows: section2),
Section(type: .section3, rows: section3),
]
}
如注释中所述发生错误是因为您无法声明具有初始值的属性,这取决于彼此。
我建议只支持init(contactData
方法。
永远不要将属性声明为隐式展开的可选项,它们在带有非可选值的init
方法中初始化。如果它们应该是可选的,则将它们声明为常规可选(?
)
class DataController1: NSObject, DataController {
struct Section {
let type: SectionTypeEnum
let rows: [Any]
}
let contactData: ContactData
var section1: [Section1]
var section2: [Section2]
var section3: [Section3]
var sections: [Section]
init(contactData: ContactData) {
self.contactData = contactData
section1 = self.contactData.list1
section2 = self.contactData.list2
section3 = self.contactData.list3
sections = [Section(type: .section1, rows: section1),
Section(type: .section2, rows: section2),
Section(type: .section3, rows: section3)]
}
}