ios - 将 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`.
}
任何建议都会有所帮助。
解决方案
协议中此属性的存在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"]
}
}
希望这可以帮助。
推荐阅读
- maven - 在 STS 中导入 Cumulocity 的“cumulocity-agents”项目后编译错误
- python - 返回新列中出现的顺序
- html - 如何在网页的下拉菜单中知道每年的具体网址
- python - 尝试创建一个基于列表生成可变数量字段的表单
- sql - 显示来自搜索 laravel 的结果
- batch-processing - 当通过邮递员提出停止请求时作业未停止
- java - 删除地图条目
> - loopback - 环回:PersistentModel - updateAll(对项目的引用)
- python - 即使在调用return时递归函数也无限运行
- string - 在 kotlin 中使用 StringBuilder 的惯用方式?