swift 简单的字典转模型

!!!本文并未提供各种字典转模型框架的功能。只是告诉你,在自己手动转换时更加安全和有效。本文提供了两种方式,如下:

一、

import Foundation
import CoreLocation

struct Venue {
    enum Category: String {
        case entertainment
        case food
        case nightlife
        case shopping
    }
    
    var name: String
    var coordinates: CLLocationCoordinate2D
    var category: Category
    init?(attributes: [String: Any]) {
        guard let name = attributes["name"] as? String,
        let coordinates = attributes["coordinates"] as? [String: Double],
        let category = Category(rawValue: attributes["category"] as? String ?? "Invalid"),
        let latitude = coordinates["latitude"],
        let longitude = coordinates["longitude"]
        else { return nil }
        
        self.name = name
        self.coordinates = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
        self.category = category
    }
    func description() -> String {
        return "name:\(name),coordinates:\(coordinates),category:\(category)"
    }
}

let JSON = "{\"name\": \"Caffè Macs\",\"coordinates\": {\"latitude\": 37.330576,\"longitude\": -122.029739},\"category\": \"food\"}"
let data = JSON.data(using: String.Encoding.utf8)!
let attributes = try! JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
if let venue = Venue(attributes: attributes) {
    print(venue.description())
}else {
    print("Here some error")
}

二、

import Foundation
import CoreLocation

enum ValidationError: Error {
    case missing(String)
    case invalid(String)
}

struct Venue {
    
    var name: String
    var coordinates: CLLocationCoordinate2D
    var category: Category
    
    enum Category: String {
        case entertainment
        case food
        case nightlife
        case shopping
    }
    
    init(attributes: [String: Any]) throws {
        guard let name = attributes["name"] as? String else {
            throw ValidationError.missing("name")
        }
        
        guard let coordinates = attributes["coordinates"] as? [String: Double] else {
            throw ValidationError.missing("coordinates")
        }
        
        guard let latitude = coordinates["lat"],
            let longitude = coordinates["lng"]
            else {
                throw ValidationError.invalid("coordinates")
        }
        
        guard let categoryName = attributes["category"] as? String else {
            throw ValidationError.missing("category")
        }
        
        guard let category = Category(rawValue: categoryName) else {
            throw ValidationError.invalid("category")
        }
        
        self.name = name
        self.coordinates = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
        self.category = category
    }
    
    func description() -> String {
        return "name:\(name),coordinates:\(coordinates),category:\(category)"
    }
}
//let JSON = "{\"name\": \"Caffè Macs\",\"coordinates\": {\"latitude\": 37.330576,\"longitude\": -122.029739},\"category\": \"food\"}"
let JSON = "{\"coordinates\": {\"latitude\": 37.330576,\"longitude\": -122.029739},\"category\": \"food\"}"
let data = JSON.data(using: String.Encoding.utf8)!
let attributes = try! JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
do {
    try Venue(attributes: attributes)
} catch ValidationError.missing(let miss) {
    print("missing:\(miss)")
}catch ValidationError.invalid(let invalid) {
    print("invalid:\(invalid)")
}

你可能感兴趣的:(swift 简单的字典转模型)