It's pretty easy, just use String
or Int
raw values which are implicitly assigned.
enum PostType: Int, Codable {
case image, blob
}
image
is encoded to 0
and blob
to 1
Or
enum PostType: String, Codable {
case image, blob
}
image
is encoded to "image"
and blob
to "blob"
This is a simple example how to use it:
enum PostType : Int, Codable {
case count = 4
}
struct Post : Codable {
var type : PostType
}
let jsonString = "{"type": 4}"
let jsonData = Data(jsonString.utf8)
do {
let decoded = try JSONDecoder().decode(Post.self, from: jsonData)
print("decoded:", decoded.type)
} catch {
print(error)
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…