Limits of Protocol Extensions and defaults in swift2

安稳与你 提交于 2019-12-05 22:45:48
DevAndArtist

I assume that fqdn is right and we won't be able to use custom inits inside protocols extension as we would like to, but only time will tell.

But there is still some workaround:

struct Meters : DistanceUnit {

    var unitType = DISTANCE_UNIT_TYPE.METER
    var value : Double
    var baseValue : Double

    init() { // this one is needed as designated initializer for your protocol extension
        value = 0
        baseValue = 0
    }
}

protocol DistanceUnit {

    var unitType : DISTANCE_UNIT_TYPE {get}
    var value : Double { get set }
    var baseValue : Double { get set }
    init() // this is new and you will NEED to implement this in your structure or class
}

extension DistanceUnit {

    init(_ v : Double) {
       self.init()
       value = v
       baseValue = v * unitType.rawValue
    }

    // you can now implement a lot more different default inits and they should work fine here :)
    // here is a quick example

    init(_ s : String) {
       self.init(Double(s.characters.count))
    }
}

Hope that will help you. I learned this trick a few days ago when i was building a custom generic singleton generator with protocol extensions (see here).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!