【发布时间】:2018-03-26 19:23:55
【问题描述】:
已在 Swift 4.1 中修复
以下描述的问题已在 Swift 4.1 中修复,请参阅 Hamish 的评论
问题
我在这段代码中遇到运行时错误:
class A: Decodable{
let a: Int
}
class B: A{
let b: Int = 1 // side problem 2: class B has no initializers.
//Why? It conforms to Decodable right??
}
func getType() -> A.Type{
return B.self
}
class Test: UIViewController{
override func viewDidLoad() {
super.viewDidLoad()
let data = ["a": 100, "b": 200]
let jsonData = try! JSONSerialization.data(withJSONObject: data)
let t = try! JSONDecoder().decode(getType(), from: jsonData)
print((t as! B).b) //run-time
}
}
因为 t 不是 B。奇怪,我返回一个 B.self。如果我打印getType(),我会得到:MyProject.B,所以虽然在我的方法签名中我返回了一个 A.Type,但它应该是一个 B.type,因为我的打印语句是这样说的。
当我删除调用 getType() 并直接放置 B.self 时,我得到完全相同的打印值。而且比我没有遇到运行时错误。
这两种方式有什么区别?为什么我直接输入 B.self 的方式 2 有效,而我的第一种方式却没有,尽管 print 语句中的值表明方式 1 和方式 2 的值是相同的。
【问题讨论】:
-
这是一个已知错误 (bugs.swift.org/browse/SR-5928),已在 Swift 4.1 中修复 - 在 Swift 4.1 中,解码器将解码
B。 -
@Hamish YES :) 谢谢你告诉我!!