imzyf / ios-swift-learning-notes

📝 iOS Swift Learning Notes - see Issues
MIT License
0 stars 0 forks source link

Codable encoding and decoding #50

Open imzyf opened 6 years ago

imzyf commented 6 years ago

http://www.jianshu.com/p/bdd9c012df15 https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types https://medium.com/@sarunw/codable-in-swift-4-0-1a12e38599d8

struct Landmark: Codable {
    var name: String
    var foundingYear: Int
    var location: Coordinate
    var vantagePoints: [Coordinate]

    enum CodingKeys: String, CodingKey {
        case name = "title"
        case foundingYear = "founding_date"

        case location
        case vantagePoints
    }
}
imzyf commented 6 years ago
do {
    let xiaoming = try JSONDecoder().decode(Student.self, from: data)
} catch {
    // 异常处理
}