【发布时间】:2017-04-08 05:55:02
【问题描述】:
这是我的代码:
class Student {
var name: String?
init (name: String) {
self.name = name
}
}
class MasterStudent: Student {
var degree: String?
init(name: String, degree: String) {
self.degree = degree
super.init(name: name, degree: degree)
}
}
fun updateStudent(stu: Student) {
var count = 0
for st in studentArray {
if (st.id == stu.id) {
studentArray.removeAtIndex(count)
st as! MasterStudent //thread 1 signal :SIGABRT
studentArray.append(stu)
}
count += 1
}
}
如果我将函数 updateStudent 传递给 Student 对象,则强制转换为 MasterStudent 会导致崩溃。我想把Student 对象变成MasterStudent 对象。
谢谢
【问题讨论】:
-
剪掉那条线。这条线是没有意义的(一个演员本身什么都不做),你没有理由在任何情况下演员。
-
我认为您滥用了基本的 OOP 编程。 MasterStudent 继承自 Student,因此您的强制向下转换可能会导致崩溃。简而言之,你不能总是从学生到硕士生沮丧。
标签: arrays swift swift2 swift3 xcode7