Swift之Codable实战技巧

时间:2021-1-8 作者:admin

struct Destination:Codable {    var  location : CLLocationCoordinate2D    var  name : String        private enum CodingKeys:String,CodingKey{        case latitude        case longitude        case name     }        public func encode(to encoder: Encoder) throws {        var container = try! encoder.container(keyedBy:CodingKeys.self)        try container.encode(name,forKey:.name)        //编码纬度         try container.encode(location.latitude,forKey:.latitude)        //编码经度         try container.encode(location.longitude,forKey:.longitude)    }         public init(from decoder: Decoder) throws {        var latitude: CLLocationDegrees        var longitude: CLLocationDegrees        let container = try decoder.container(keyedBy: CodingKeys.self)        latitude = try container.decode(CLLocationDegrees.self,forKey:.latitude)        longitude = try container.decode(CLLocationDegrees.self,forKey:.longitude)         self.location = CLLocationCoordinate2D(latitude:latitude,longitude:longitude)        self.name = try container.decode(String.self,forKey:.name)    }}

声明:本文内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎进行举报,并提供相关证据,工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。