Json as array Type ?

Is this possible ? ...

static func loadJSON<T>(_ url: URL, arrayType: T.Type)
let json_array: [AnyObject] = try JSONDecoder().decode(Array<T>.self, from: json_data)


Trying to make my loading func a bit more dynamic.

Accepted Reply

The code should work as expected (though it is not clear enough what you expect) only if `T` is `Decodable`:


    static func loadJSON<T: Decodable>(_ url: URL, arrayType: T.Type) {
        do {
            let json_data = Data()
            //...
            let json_array: [T] = try JSONDecoder().decode(Array<T>.self, from: json_data)
            //...
        } catch {
            print(error)
            //...
        }
    }


But what do you expect with this code? Generic parameters are resolved statically and it may not be so dynamic.

Replies

The code should work as expected (though it is not clear enough what you expect) only if `T` is `Decodable`:


    static func loadJSON<T: Decodable>(_ url: URL, arrayType: T.Type) {
        do {
            let json_data = Data()
            //...
            let json_array: [T] = try JSONDecoder().decode(Array<T>.self, from: json_data)
            //...
        } catch {
            print(error)
            //...
        }
    }


But what do you expect with this code? Generic parameters are resolved statically and it may not be so dynamic.

Works with <T: Codable> thank you. 🙂