在父類的便利初始值設定項中,如何在調用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 {
}
使用「is」關鍵字:http://stackoverflow.com/a/24097894/2351432 –
你不應該相信。超類應該對它的子類一無所知。 –
@MattLogan「self is Car」會引發錯誤,因爲在init()之前不允許使用'self'。但我發現'self.dynamicType'是。請參閱下面的答案。 – SuitedSloth