【问题标题】:swift downcast issue from superclass to subclass从超类到子类的快速沮丧问题
【发布时间】: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


【解决方案1】:

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

我还添加了一些示例代码,说明当实例化一个向上转换为Student 并随后向下转换为MasterStudent 的MasterStudent 对象时,该代码不会失败。但是,实例化 Student 对象在向下转换为 MasterStudent 时将失败。它不是正确的类型。这样想,我稍微简化一下——Student 实例缺少匹配MasterStudent 行为所需的degree 属性。

as! 运算符仅应在确定向下转换将成功时使用。这是一个这样的例子:

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

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

【讨论】:

  • 首先感谢您的快速回答,我看到了您在沙箱中写的内容,当您使用更新功能时,您发送 MasterStudent 对象而不是 Student 对象,我需要发送一个 Student 并转换它给 MasterStudent 所以我从数组中删除了前一个学生,需要添加一个 MasterStudent 以及所有其他字段再次感谢
  • 我从您的 privious 评论中了解到,学生无法转换为 MasterStudent,即使缺少专业学位,我该怎么做才能将 Student 更新为 MasterStudent
  • 我创建了另一个沙盒快照here,它创建了一个新的 MasterStudent 对象而不是向下转换。请注意,如果未传入 degree 参数,则 MasterStudent 初始值设定项现在具有默认度值“Masters”。
【解决方案2】:

如果st 对象已经是MasterStudent 的实例,则只能将st 向下转换为MasterStudent。否则你需要创建一个新的MasterStudent 对象:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-19
    • 2011-05-08
    • 2012-04-02
    • 2012-04-03
    • 1970-01-01
    • 2016-07-07
    相关资源
    最近更新 更多