Fixed in Swift 4.1
The issue described below is fixed in Swift 4.1, see Hamish comment
Problem
I get a runtime error for this code:
class A: Decodable{
let a: Int
}
class B: A{
let b: Int = 1
}
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)
}
}
Since t is not B. Strange, I return a B.self. If I print getType(), I get the following: MyProject.Btherefore, although in my method signature I return A.Type, it should be B.type, as my print statement says so.
I get the exact same print value when I delete the call getType()and directly place B.self. And how can I not get a runtime error.
? 2, B.self, , , , 1 2 .