微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

swift – 为超类创建初始化器返回一个特定的子类?

参见英文答案 > Custom class clusters in Swift                                    4个
我正在Swift中创建一个单元框架,它有不同单位的测量超类和子类,如Mass和Volume.一个功能是允许框架正确猜测它创建的单元并返回正确的类.示例代码

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

是否有可能让一个继承的类在初始化时创建特定子类的对象?

Library在GitHub上命名为Indus Valley和开源

解决方法

它正在快速而松散地继承,让父类知道它的子类(非常差的反模式!)但这可行…

class Measurement {
    var unitString : String

    class func factory(unkNownUnit: String) -> Measurement {
        if unkNownUnit == "kg" {
            return Mass(myUnit: unkNownUnit)
        } else { // Random default,or make func return Measurement? to trap
            return Volume(myUnit: unkNownUnit)
        }
    }

    init(myUnit: String) {
        // checks if the unit is either Volume or Mass,and returns an instance of that class
        self.unitString = myUnit
    }
}

class Volume : Measurement {
}

class Mass : Measurement {
}

let mass = Mass(myUnit: "kg")                   // class: Mass
let volume = Volume(myUnit: "ml")               // class: Volume
let shouldntBeVolume = Measurement(myUnit: "ml")  // class: Measurement
let shouldntBeMass = Measurement(myUnit: "kg")    // class: Measurement
let isVolume = Measurement.factory("ml")  // class: Volume
let shouldBeMass = Measurement.factory("kg")    // class: Mass

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐