默认情况下,Decodable协议将JSON值转换为对象值而不进行任何更改.但有时您需要在json解码期间转换值,例如,在JSON中,{id = "id10"}但是在您的类实例中,您需要将数字10放入属性id(或者使用不同名称的偶数属性).
您可以init(from:)使用任何值实现可以执行所需操作的方法,例如:
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
latitude = try container.decode(Double.self, forKey:.latitude)
longitude = try container.decode(Double.self, forKey: .longitude)
// and for example there i can transform string "id10" to number 10
// and put it into desired field
}
Run Code Online (Sandbox Code Playgroud)
这听起来对我来说很棒,但是如果我只想为其中一个 JSON字段更改值并将所有其他20个字段保留为没有变化,该怎么办?如果init(from:)我应该手动获取并为我班级的20个字段中的每个字段添加值!经过多年的objC编码,我直接调用super的实现,init(from:)然后对某些字段进行更改,但是如何使用Swift和Decodable协议实现这样的效果呢?
一种书呆子的问题.我不清楚,这段代码的确切作用是什么:
class Shape { }
extension Shape {
@objc func redraw() {
print("from ext")
}
}
class Circle: Shape { }
class Line: Shape {
override func redraw() { // Compiler error: Declarations from extensions cannot be overridden yet
print("from subclass")
}
}
let line = Line()
let shape:Shape = line
let circle = Circle()
line.redraw() //from subclass
circle.redraw() //from ext
shape.redraw() //from subclass
Run Code Online (Sandbox Code Playgroud)
如果我@objc在扩展中省略了关键字,代码将无法编译 - 这是预期的行为,因为扩展中的方法使用静态方法dispatch - >无法覆盖.但为什么添加@objc使它工作?根据文档和大多数文章,所有正在@objc做的是使Objective-c运行时可见.要更改方法分派类型,有一个特殊的关键字 - dynamic.但似乎这里没有必要!
帮助我弄清楚,为什么添加@objc …
我需要得到NSSearchField的这种外观

但似乎不可能使用Interface Builder的标准方法设置backgroundColor.我怎么能做到这一点?子类化NSSearchField和NSSearchFieldCell没有帮助,因为在实现我自己的绘制方法时,我放松了所有动画(当你点击搜索字段和图标+文本向左滑动时).