【发布时间】:2015-05-25 11:29:20
【问题描述】:
我正在用 Swift 制作一个单位框架,它具有不同单位的测量超类和子类,例如质量和体积。一个功能是允许框架正确猜测它是用什么单元创建的并返回正确的类。示例代码:
class Measurement {
var unitString : String
init(unknownUnit: String) {
// checks if the unit is either Volume or Mass, and returns an instance of that class
}
}
class Volume : Measurement {
init(unitString: String) {
}
}
class Mass : Measurement {
init(unitString: String) {
}
}
let mass = Mass("kg") // class: Mass
let volume = Volume("ml") // class: Volume
let shouldBeVolume = Measurement("ml") // class: Volume
let shouldBeMass = Measurement("kg") // class: Mass
是否可以让继承的类在初始化时创建特定子类的对象?
库名为Indus Valley,在 GitHub 上开源
【问题讨论】:
-
这绝对是 Swift
init不返回值的一个恼人限制。