首页 > 解决方案 > 将 swift 协议属性覆盖为可选

问题描述

我正在使用这个库,https://github.com/gcharita/XMLMapper

它包含协议,

public protocol XMLBaseMappable {
    var nodeName: String! { get set }
}

我想nodeName为实现它的结构/类设置此选项,例如

public protocol CustomXMLBaseMappable {
    var nodeName: String? { return "default" }

    //I don't want struct/classes using it, implements `nodeName`.
}

任何建议都会有所帮助。

标签: iosswiftxmlcodablexmlmapper

解决方案


协议中此属性的存在XMLBaseMappable对于整个库的正常运行至关重要。

话虽如此,您不能在结构和类中省略此属性的实现,但您可以将其“隐藏”在超类中。使用这个:

class BasicXMLMappable: XMLMappable {
    var nodeName: String!

    required init(map: XMLMap) {

    }

    func mapping(map: XMLMap) {

    }
}

您可以拥有XMLMappable扩展的对象,BasicXMLMappable并且它们不必实现nodeName属性:

class TestBasicXMLMappable: BasicXMLMappable {

    // Your custom properties

    required init(map: XMLMap) {
        super.init(map: map)
    }

    override func mapping(map: XMLMap) {
        // Map your custom properties
    }
}

编辑: 从 1.5.1 版开始,您可以XMLStaticMappable用于XMLMapper在扩展中实现。例如:

class CustomClass {
    var property: String?
}

extension CustomClass: XMLStaticMappable {
    var nodeName: String! {
        get {
            return "default"
        }
        set(newValue) {

        }
    }

    static func objectForMapping(map: XMLMap) -> XMLBaseMappable? {
        // Initialize CustomClass somehow
        return CustomClass()
    }

    func mapping(map: XMLMap) {
        property <- map["property"]
    }
}

希望这可以帮助。


推荐阅读