Return dynamic generic type

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 // 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
    }
}

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 .

+4
1

JSONDecoder.decode() - , . , getType() , .

Decodable , , , , .

, :

func decode(from data: Data, type: A.Type) throws {
    let decoder = JSONDecoder()
    if type == A.self { return try decoder.decode(data, type: A.self) }
    else if type == B.self { return try decoder.decode(data, type: B.self) }
    else { throw TypeNotSupportedError }
}

- .

# 2, , Codable .

0

Source: https://habr.com/ru/post/1695366/


All Articles