Kodeco Forums

Encoding, Decoding and Serialization in Swift 4

Learn how to encode, decode and serialize data in Swift 4!


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/382-encoding-decoding-and-serialization-in-swift-4

Thanks so much.

But I have a question:

  • How can I make the no need be codable properties restore within the instance?

Ex: I have a User struct with some properties like id, name and so on, it has many properties but I need only some be coded/encoded, if I conformed the Codable protocol, I must implement CodingKeys and encode/decode all the properties.

Follow is my solution:

extension GitHubUser: Decodable{
	init(from decoder: Decoder) throws {
		let values = try decoder.container(keyedBy: CodingKeys.self)
		id = try values.decode(Int.self, forKey: .id)
		type = try values.decode(String.self, forKey: .type)
		loginName = try values.decode(String.self, forKey: .loginName)
		avatarUrl = try values.decode(String.self, forKey: .avatarUrl)
		homepageUrl = try values.decode(String.self, forKey: .homepageUrl)
		profileUrl = try values.decode(String.self, forKey: .profileUrl)
		
		// optional decodable properties operation
		do {
			name = try values.decode(String.self, forKey: .name)
		}catch{
			name = ""
		}
		
		do {
			company = try values.decode(String.self, forKey: .company)
		}catch{
			company = ""
		}
		
		do {
			location = try values.decode(String.self, forKey: .location)
		}catch{
			location = ""
		}
		
		do{
			blog = try values.decode(String.self, forKey: .blog)
		}catch{
			blog = ""
		}
		
		do{
			bio = try values.decode(String.self, forKey: .bio)
		}catch{
			bio = ""
		}
	}
}

So how could I get another more elegant solution except that?

just make them optional

is it good idea to just use extention so we will not use

extension Encodable {
 var jsonData: Data? {
     let encoder = JSONEncoder()
     do {
         return try encoder.encode(self)
     } catch {
         print(error.localizedDescription)
         return nil
     }
 }
 
 var jsonString: String? {
     guard let data = self.jsonData else { return nil }
     return String(data: data, encoding: .utf8)
 }
}

extension Decodable {
 static func from(json: String, using encoding: String.Encoding = .utf8) -> Self? {
     guard let data = json.data(using: encoding) else { return nil }
     return Self.from(data: data)
 }
 
 static func from(data: Data) -> Self? {
     let decoder = JSONDecoder()
     do {
         return try decoder.decode(Self.self, from: data)
     } catch {
         print(error.localizedDescription)
         return nil
     }
     
 }
}

This tutorial is more than six months old so questions are no longer supported at the moment for it. Thank you!