在Swift类中获取和设置数组

时间:2017-06-22 01:11:26

标签: swift class oop

我构建了一个IOS应用程序,不知怎的,我必须在swift类中进行聚合,但每次我想获取数据时,它总是返回错误。似乎我的数据总是返回一个零结果。

我想在视图控制器类中推送DoctorList成员对象(schedule) 我已经创建了对象,我也调用了init()函数。但是,当我按下(或调用)DoctorList类的init函数并传递ScheduleList数组时,doctorlist类中的schedule成员的内容将始终为空。

所以当我试图获得时间表时,它将返回一个零结果。

每个人都可以告诉我我做错了什么,因为我已经更改了代码,但它仍然没有结果。

我有两个这样的课程

class DoctorList: NSObject {
var DoctorID: String?
var DoctorName: String?
var SpecialtyID: String?
var SpecialtyName: String?
var ImageURL: String?
var Schedule: [ScheduleList]?

init(_ DoctorID:String, _ DoctorName:String, _ SpecialtyID:String, _ SpecialtyName:String, _ ImageUrl:String, _ Schedule:[ScheduleList] ){
    self.DoctorID = DoctorID
    self.DoctorName = DoctorName
    self.SpecialtyID = SpecialtyID
    self.SpecialtyName = SpecialtyName
    self.ImageURL = ImageUrl
    for sc in Schedule {
        self.Schedule?.append(ScheduleList(sc.DoctorID!, sc.DayName!, sc.FirstHour!, sc.LastHour!))
    }

}

var getSchedule: [ScheduleList] {
    get {
        return self.Schedule!
    }

}

和这一个

class ScheduleList: NSObject {
var DoctorID: String?
var DayName: String?
var FirstHour: String?
var LastHour: String?

init(_ DoctorID:String, _ DayName:String, _ FirstHour:String, _ LastHour:String ){
    self.DoctorID = DoctorID
    self.DayName = DayName
    self.FirstHour = FirstHour
    self.LastHour = LastHour
}

计划的返回值始终为空

对不起,有人可以提出如何在swift中创建全局变量的建议吗?

2 个答案:

答案 0 :(得分:4)

您尚未初始化Schedule数组。

循环中的append语句永远不会执行:

for sc in Schedule {
    // self.Schedule is nil so anything come after the question mark does not run
    self.Schedule?.append(ScheduleList(sc.DoctorID!, sc.DayName!, sc.FirstHour!, sc.LastHour!))
}

要修复它,请在使用前初始化数组:

self.Schedule = [ScheduleList]()
for sc in Schedule {
    self.Schedule?.append(ScheduleList(sc.DoctorID!, sc.DayName!, sc.FirstHour!, sc.LastHour!))
}

此外,您的代码很难阅读:

  • 无处不在的选择!您应该决定哪些属性可以和不可以为零并删除不必要的?!
  • Swift中的约定对于变量名称为lowerCamelCase,对于类名称为CamelCase
  • 除非您想要ObjC世界的某些东西,无论是使用ObjC还是使用KVO,否则无需继承NSObject

答案 1 :(得分:2)

刚刚注意到,来自@CodeDifferent的建议应该是恰当和有用的。 这是因为您尚未初始化Schedule

中的DoctorList
init(_ DoctorID:String, _ DoctorName:String, _ SpecialtyID:String, _ SpecialtyName:String, _ ImageUrl:String, _ Schedule:[ScheduleList] ){
        self.DoctorID = DoctorID
        self.DoctorName = DoctorName
        self.SpecialtyID = SpecialtyID
        self.SpecialtyName = SpecialtyName
        self.ImageURL = ImageUrl

        // Use this for init an empty array and append the content
        self.Schedule = [ScheduleList]()
        self.Schedule?.append(contentsOf: Schedule)
    }

结果的一个例子:

let schedule = ScheduleList("scheduleId", "name", "1st", "last")
let doctorList = DoctorList("docId", "docName", "specId", "scpecName", "imgURL", [schedule])
if let list = doctorList.Schedule {
    print("\(list[0].DoctorID)")
}