从超类到子类的快速转发问题

时间:2016-11-24 03:49:08

标签: arrays swift swift2 swift3 xcode7

这是我的代码:

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对象。

谢谢

2 个答案:

答案 0 :(得分:2)

代码不会按原样编译,因此我做了一些小的调整,并将其更新到IBM Swift Sandbox here中的Swift 3。

我还添加了一些示例代码,演示了在将MasterStudent对象转发为Student然后向下转换为MasterStudent时,代码不会失败。但是,实例化Student对象在向下转换为MasterStudent时将失败。它不是正确的类型。以这种方式考虑,我简化了一点 - Student实例缺少匹配degree行为所需的MasterStudent属性。

只有在确定向下转发成功时才应使用as!运算符。这是一个这样的例子:

let obj:Any = "Hello World"
let obj2 = obj as! String

使用as!运算符时,编译器信任您的判断,不会提供编译时错误。如果向下转换不成功,您的用户将收到运行时异常,这通常是要避免的。 as?运算符是一种更安全的选择,因为如果不成功,它将向下转发或返回nil

答案 1 :(得分:1)

如果st对象已经是MasterStudent的实例,则您只能将st转发给MasterStudent。否则,您需要创建一个新的MasterStudent对象:

MasterStudent(name: st.name, degree: "...")