'I want to use enum value as type in Swift
I defined this structure.
import Foundation
import SwiftUI
struct Hoge: Hashable, Codable {
var id: Int
var type: Type
}
enum Type: Codable {
case one
case two
}
And I created json.
[
{
"id": 1,
"type": "one",
},
...
]
And this is decode and load json file.
import Foundation
var hogeList: [Hoge] = load("hoge.json")
func load<T: Decodable>(_ filename: String) -> T {
let data: Data
guard let file = Bundle.main.url(forResource: filename, withExtension: nil) else {
fatalError("Couldnt find \(filename) in main bundle.")
}
do {
data = try Data(contentsOf: file)
} catch {
fatalError("Couldnt load \(filename) from main bundle:\n\(error)")
}
do {
let decoder = JSONDecoder()
return try decoder.decode(T.self, from: data)
} catch {
fatalError("Couldnt parse \(filename) as \(T.self):\n\(error)")
}
}
Crach logs shows this logs.
Fatal error: Couldnt parse hoge.json as Array: typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "type", intValue: nil)], debugDescription: "Expected to decode Dictionary<String, Any> but found a string/data instead.", underlyingError: nil))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
