2016-11-24 64 views
0

這是我的代碼:迅速沮喪的問題繼承

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

感謝

+0

只要切斷那條線。這條線是沒有意義的(一個單獨的演員什麼也不做),並且你無論如何都沒有理由演員。 – matt

+0

我認爲你濫用基本的OOP編程。 MasterStudent從Student繼承,所以你的**被強制downcast **可能導致崩潰。簡單地說,你不能總是從學生向MasterStudent低調。 – dfd

回答

2

的代碼將無法正常編譯,對我來說,讓我在IBM斯威夫特沙盒here做了一些小的調整和更新,它斯威夫特3。

我還添加了一些示例代碼表明實例化一個MasterStudent對象,它是向上轉型到Student,然後向下轉換到一個MasterStudent當代碼不會失敗。但是,實例化一個Student對象時,將向下轉換爲MasterStudent時會失敗。它不是正確的類型。想想這樣,我簡化了一點 - Student實例缺少degree屬性,它需要與MasterStudent的行爲相匹配。

as!操作員只有在確定downcast會成功時才能使用。這裏就是這樣一個例子:

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

當使用as!操作,編譯器相信你的判斷,並不會提供一個編譯時錯誤。如果downcast不成功,您的用戶將收到運行時異常,這通常是要避免的。 as?運營商是更安全的選擇,因爲如果不成功,它將向下或返回nil

+0

首先感謝您的快速回答,我看到您在沙箱中寫的內容,並且當您使用更新功能發送MasterStudent對象而不是Student對象時,我需要的是發送一個學生並將其轉換爲MasterStudent,以便從該陣列的前一名學生,需要添加一個MasterStudent與所有額外的領域再次感謝 – user7024226

+0

我從你的私人評論理解,學生不能轉換爲MasterStudent,我該怎麼做才能更新學生MasterStudent即使外地學位缺乏 – user7024226

+0

我創建了另一個沙盒快照[這裏](http://swift.sandbox.bluemix.net/#/repl/5836feca27a1b233cd0fa980),它創建了一個新的MasterStudent對象而不是向下轉換。請注意,如果未傳入「度量」參數,則MasterStudent初始化程序現在具有默認度數值「Masters」。 –

1

你只能垂頭喪氣stMasterStudent如果它st對象已經是MasterStudent一個實例。否則,你將需要創建一個新的MasterStudent對象:

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