2016-08-18 59 views
1

在父類的便利初始值設定項中,如何在調用self.init()之前確定當前類?如何確定快速初始化程序中的自我類

public class Vehicle { 

    public convenience init(withDictionary rawData: [String:AnyObject]) { 

     // how do I determine whether this is a Car here? 

     self.init() 

    } 

} 

public class Car: Vehicle { 

} 

public class Bike: Vehicle { 

} 
+0

使用「is」關鍵字:http://stackoverflow.com/a/24097894/2351432 –

+1

你不應該相信。超類應該對它的子類一無所知。 –

+0

@MattLogan「self is Car」會引發錯誤,因爲在init()之前不允許使用'self'。但我發現'self.dynamicType'是。請參閱下面的答案。 – SuitedSloth

回答

0

看起來像使用self.dynamicType被允許:

public class Vehicle { 

    public convenience init(withDictionary rawData: [String:AnyObject]) { 

     let myType = self.dynamicType 

     print("This is a \(myType)") 

     self.init() 

    } 

} 

public class Car: Vehicle { 

} 

public class Bike: Vehicle { 

} 

let car = Car(withDictionary: ["key":"value"]) 

// prints "This is a Car" 
0

你需要使用「是」運營商確定的那種類的。

public class Vehicle 
{ 

    public convenience init(withDictionary rawData: [String:AnyObject]) 
    { 

    self.init() 

    if self is Car 
    { 
     print("It's a car") 
    } 
    else if self is Bike 
    { 
     print("It's a bike") 
    } 

    } 
} 

但是,您也可以在汽車或自行車的初始化函數中進行初始化。

+0

代碼可以在self.init()調用之前運行,這很重要。同樣'self.dynamic'允許使用類型,而不必枚舉每個可能的子類以確定它是哪一個。 – SuitedSloth

相關問題