SwiftUI adding Codable conformance for #Published properties using 'id' property - swift

I'm just starting out on learning SwiftUI. Where do I go wrong?
I'm trying to add Codable conformance in my class (ManyItems). This so I eventually can save an array to disk using JSON.
Two errors:
1) In both the "required init(...) "id = try..." and the encode func: "try container.encode..." result in "'id' is unavailable in Swift: 'id' is not available in Swift; use 'Any'"
2) In both the required init(...) and func encode: "Use of unresolved identifier 'one'." I assumed the identifier in the struct would be carried forward into the class?
struct Item: Identifiable {
var id = UUID()
var one: String
}
class ManyItems: ObservableObject, Codable {
#Published var manyitems = [Item]()
enum CodingKeys: CodingKey {
case id
case one
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(UUID.self, forKey: .id)
one = try container.decode(String.self, forKey: .one)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(id, forKey: .id)
try container.encode(one, forKey: .one)
}
}

I've found a solution but had to take a slightly different route. Hopefully this could help someone else who needs to use a Collection conforming to Codable and ObservableObject for saving to the Apps documentDirectory.
I conformed the struct 'Item' to Codable (i.e not the class 'ManyItem'). I added code for JSON encoding and saving of the Collection to the Apps documentDirectory. This happens automatic when a property value changes. The class is initiated through either a read/decoding of the JSON file from the Apps document directory or as a new blank instance if the JSON file is not available yet.
struct Item: Identifiable, Codable {
var id = UUID()
var one: String
}
class ManyItems: ObservableObject {
#Published var manyitems: [Item] {
didSet {
// Saves the array 'items' to disc
do {
// find the documentDirectory and create an URL for the JSON
file
let filename = getDocumentsDirectory().appendingPathComponent("manyitems.json")
let data = try JSONEncoder().encode(self.manyitems)
try data.write(to: filename, options: [.atomicWrite])
} catch {
print("Unable to save data.")
}
}
}
init() {
// replaces a call to 'getDocumentsDirectory()' methode as it created an initialisation error.
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
// Add the first [0] path to the filename and create 'filename'
let filename = paths[0].appendingPathComponent("manyitems.json")
//print(filename)
do {
// Try to read the file (if it exist) and load the data into the array 'manyitem'
let data = try Data(contentsOf: filename)
manyitems = try JSONDecoder().decode([Item].self, from: data)
// Yes all good then exit
return
} catch {
// Something whent wrong. Initialize by creating an empty array 'manyitems'
self.manyitems = []
print("Unable to load saved data.")
}
}
// retreives the App's first DocumentDirectory
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}
}

Your Codable models should be,
struct Item: Codable, Identifiable {
var id = UUID()
var one: String
}
class ManyItems: Codable, ObservableObject {
#Published var manyitems = [Item]()
}
As evident from your code, you're not handling any specific parsing cases. So, there is no need to explicitly implement init(from:) and encode(to:) methods.

Related

Issue converting custom type array into data | Swift

Essentially I would like to convert an array of the following custom struct into data for data for easier saving in CoreData as Binary Data. How can the following be converted into data to then be ready to decode back:
Custom Struct
struct Place: Codable, Identifiable {
var id = UUID()
var coordinate: Coordinate
struct Coordinate: Codable {
let latitude: Double
let longitude: Double
func locationCoordinate() -> CLLocationCoordinate2D {
return CLLocationCoordinate2D(latitude: self.latitude,
longitude: self.longitude)
}
}
}
Adding to Custom Struct
var mapAddresses = [Place]()
Task {
mapAddresses.append(Place(coordinate: try await getCoordinate(from:
post.location)))
}
The issue I am having is converting the array mapAddresses with the custom structure into Binary Data, that can then be decoded back into the custom array.
In comments, your phrasing indicates that you want a binary encoding. I'll get to that, but first let's just encode/decode JSON.
Given
struct Place: Codable {...}
let mapAddresses: [Place] = ...
The following code encodes mapAddresses, then immediately decodes the resulting Data:
guard let data = try? JSONEncoder().encode(mapAddresses) else {
fatalError("Failed to encode")
}
guard let decodedMapAddresses =
try? JSONDecoder().decode([Place].self, from: data)
else { fatalError("Failed to decode") }
Whether data is binary is a matter of interpretation. data will just contain the text of the JSON representing mapAddresses. Technically text is binary, but then again so is anything else in a computer. What we normally mean is non-text, that is some more compact or more directly machine-friendly encoding that is not so human-friendly. JSONEncoder doesn't provide such a facility, but PropertyListEncoder does, via it's outputFormat property. To use it:
let encoder = PropertlyListEncoder()
encoder.outputFormat = .binary
guard let data = encoder.encode(mapAddresses) else {
fatalError("Failed to encode")
}
guard let decodedMapAddresses =
try? PropertyListDecoder().decode([Place].self, from: data)
else { fatalError("Failed to decode") }
Note there is no need specify that it's binary in the decoder, because PropertyListDecoder knows how to detect that.
Like others have said in the comments, you don't have a fully-formed question yet. But first, you don't need Coordinate. Just make CLLocationCoordinate2D Codable, like Apple should have.
import struct CoreLocation.CLLocationCoordinate2D
public extension CLLocationCoordinate2D {
enum CodingKey: Swift.CodingKey {
case latitude
case longitude
}
}
extension CLLocationCoordinate2D: Decodable {
public init(from decoder: Decoder) throws {
try self.init(
Self.init, (CodingKey.latitude, .longitude),
decoder: decoder
)
}
}
extension CLLocationCoordinate2D: Encodable {
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKey.self)
try container.encode(latitude, forKey: .latitude)
try container.encode(longitude, forKey: .longitude)
}
}
public extension Decodable {
/// Initialize using 2 keyed, decoded arguments.
/// - Parameters:
/// - init: An initializer (or factory function) whose arguments are the decoded values.
/// - keys: `CodingKey` instances, matching the arguments.
init<
Parameter0: Decodable, Parameter1: Decodable, Key: CodingKey
>(
_ init: (Parameter0, Parameter1) -> Self,
_ keys: (Key, Key),
decoder: Decoder
) throws {
let container = try decoder.container(keyedBy: Key.self)
self = try `init`(
container.decode(forKey: keys.0),
container.decode(forKey: keys.1)
)
}
}
public extension KeyedDecodingContainerProtocol {
/// Decode, relying on the return type, to avoid having to explicitly use a metatype argument.
func decode<Decodable: Swift.Decodable>(forKey key: Key) throws -> Decodable {
try decode(Decodable.self, forKey: key)
}
}

SwiftUI: Encode a struct to be saved in AppStorage

Currently trying to build my first app in swiftUI. The part I thought would be the easiest as become a nightmare... save a struct in AppStorage to be available upon restart of the app
I got two struct to save. The first is for player and I have implemented the RawRepresentable
struct Player: Codable, Identifiable {
let id: Int
let name: String
let gamePlayed: Int
let bestScore: Int
let nbrGameWon: Int
let nbrGameLost: Int
let totalScore: Int?
}
typealias PlayerList = [Player]
extension PlayerList: RawRepresentable {
public init?(rawValue: String) {
guard let data = rawValue.data(using: .utf8),
let result = try? JSONDecoder().decode(PlayerList.self, from: data)
else {
return nil
}
self = result
}
public var rawValue: String {
guard let data = try? JSONEncoder().encode(self),
let result = String(data: data, encoding: .utf8)
else {
return "[]"
}
return result
}
}
Calling in my view this way:
struct AddPlayerView: View {
#State var name: String = ""
#State var isDisabled: Bool = false
#State var modified: Bool = false
#AppStorage("players") var players: PlayerList = PlayerList()
...
}
The above works, now I also want to save the current game data, I have the following struct:
struct Game: Codable, Identifiable {
var id: Int
var currentPlayerIndexes: Int
var currentRoundIndex: Int?
var dealerIndex: Int?
var maxRounds: Int?
var dealResults: [Int: Array<PlayerRoundSelection>]?
var currentLeaderIds: Array<Int>?
var isGameInProgress: Bool?
}
extension Game: RawRepresentable {
public init?(rawValue: String) {
if rawValue == "" {
// did to fix issue when calling AppStorage, but it is probably a bad idea
self = Game(id:1, currentPlayerIndexes:1)
}
else {
guard let data = rawValue.data(using: .utf8),
let result = try? JSONDecoder().decode(Game.self, from: data)
else {
return nil
}
self = result
}
}
public var rawValue: String {
guard let data = try? JSONEncoder().encode(self),
let result = String(data: data, encoding: .utf8)
else {
return ""
}
return result
}
}
As soon as I try to modify the struct, it calls rawValue and the encoding fails with the following:
error: warning: couldn't get required object pointer (substituting NULL): Couldn't load 'self' because its value couldn't be evaluated
error: Execution was interrupted, reason: EXC_BAD_ACCESS (code=2, address=0x7ffee49bbff8).
Here part of the code that access the struct:
struct SelectPlayersView: View {
#AppStorage("currentGame") var currentGame: Game = Game(rawValue: "")!
....
NavigationLink(
destination: SelectModeTypeView(), tag: 2, selection: self.$selection) {
ActionButtonView(text:"Next", disabled: self.$isDisabled, buttonAction: {
var currentPlayers = Array<Int>()
self.players.forEach({ player in
if selectedPlayers.contains(player.id) {
currentPlayers.insert(player.id, at: currentPlayers.count)
}
})
// This used to be a list of indexes, but for testing only using a single index
self.currentGame.currentPlayerIndexes = 6
self.selection = 2
})
...
I found the code to encode here: https://lostmoa.com/blog/SaveCustomCodableTypesInAppStorageOrSceneStorage/
My understanding is that with the self in the encode, it generate an infinite loop hence the bad access.
I have really no knowledge how to properly encode this, any help, links would be appreciated
I had the same problem and I wanted to share my experience here.
I eventually found that apparently you cannot rely on the default Codable protocol implementation when used in combination with RawRepresentable.
So when I did my own Codable implementation, with CodingKeys and all, it worked!
I think your Codable implementation for Game would be something like:
enum CodingKeys: CodingKey {
case currentPlayerIndexes
case currentRoundIndex
// <all the other elements too>
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.currentPlayerIndexes = try container.decode(Int.self, forKey: .currentPlayerIndexes)
self.currentRoundIndex = try container.decode(Int.self, forKey: .currentRoundIndex)
// <and so on>
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(currentPlayerIndexes, forKey: .currentPlayerIndexes)
try container.encode(currentRoundIndex, forKey: .currentRoundIndex)
// <and so on>
}
I then wondered why your Player coding/decoding did work and found that the default coding and decoding of an Array (i.e. the PlayerList, which is [Player]), works fine.

SwiftUI ObservableObject create non array #Published

I tried to create an ObservableObject with non array #Published item. However, I still don't know how to do so. I tried to use a ? to do so. But when I display it in view like Text((details.info?.name)!), and it return Thread 1: Swift runtime failure: force unwrapped a nil value I don't know what the problem and how to solve. Is it my method of creating observable object class are correct?
class ShopDetailJSON: ObservableObject {
#Published var info : Info?
init(){load()}
func load() {
URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else {
print("No data in response: \(error?.localizedDescription ?? "Unknown error").")
return
}
if let decodedShopDetails = try? JSONDecoder().decode(ShopDetail.self, from: data) {
DispatchQueue.main.async {
self.info = decodedShopDetails.info!
}
} else {
print("Invalid response from server")
}
}.resume()
}
}
struct Info : Codable, Identifiable {
let contact : String?
let name : String?
var id = UUID()
enum CodingKeys: String, CodingKey {
case contact = "contact"
case name = "name"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
contact = try values.decodeIfPresent(String.self, forKey: .contact)
name = try values.decodeIfPresent(String.self, forKey: .name)
}
}
struct ShopDetail : Codable {
let gallery : [Gallery]?
let info : Info?
enum CodingKeys: String, CodingKey {
case gallery = "gallery"
case info = "info"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
gallery = try values.decodeIfPresent([Gallery].self, forKey: .gallery)
info = try values.decodeIfPresent(Info.self, forKey: .info)
}
}
Sample JSON data
{
"gallery": [],
"info": {
"contact": "6012345678",
"name": "My Salon",
}
}
This is answer is a bit of a guess as to what happens in your code, but if the JSON data is never null, as you say in the comments, it's likely that you're trying to access a not-yet-updated ShopDetailJSON.info optional property in your view.
First, some clean-up. You don't need to the custom implementation of init(from:) - just conforming to Codable is enough in your case. And if the JSON values aren't optional, no need to make them into an optional type:
struct Info: Codable, Identifiable {
let contact : String
let name : String
var id = UUID()
}
struct ShopDetail: Codable {
let gallery : [Gallery]
let info : Info
}
Then, when you get the JSON you wouldn't need to deal with optionals and force-unwrap ! (which should have been avoided anyways):
if let decodedShopDetails = try? JSONDecoder().decode(ShopDetail.self, from: data {
DispatchQueue.main.async {
self.info = decodedShopDetails.info // no force-unwrap needed
}
}
In the view, you need to check that the info property is not nil before accessing its elements.
struct ContentView: View {
#ObservedObject var details: ShopDetailJSON
var body: some View {
Group() {
// on iOS14
if let info = details.info {
Text(info.name)
}
// pre iOS14
// if details.info != nil {
// Text(details.info!.name)
// }
}
.onAppear {
self.details.load()
}
}
}

How to encode/decode a dictionary with Codable values for storage in UserDefaults?

I am trying to store a dictionary of company names (string) mapped to Company objects (from a struct Company) in iOS UserDefaults. I have created the Company struct and made it conform to Codable. I have one example a friend helped me with in my project where we created a class Account and stored it in UserDefaults by making a Defaults struct (will include example code). I have read in the swift docs that dictionaries conform to Codable and in order to stay Codable, must contain Codable objects. That is why I made struct Company conform to Codable.
I have created a struct for Company that conforms to Codable. I have tried using model code to create a new struct CompanyDefaults to handle the getting and setting of the Company dictionary from/to UserDefaults. I feel I have some beginner misconceptions about what needs to happen and about how it should be implemented (with good design in mind).
The dictionary I wish to store looks like [String:Company]
where company name will be String and a Company object for Company
I used conform to Codable as I did some research and it seemed like a newer method for completing similar tasks.
Company struct
struct Company: Codable {
var name:String?
var initials:String? = nil
var logoURL:URL? = nil
var brandColor:String? = nil // Change to UIColor
enum CodingKeys:String, CodingKey {
case name = "name"
case initials = "initials"
case logoURL = "logoURL"
case brandColor = "brandColor"
}
init(name:String?, initials:String?, logoURL:URL?, brandColor:String?) {
self.name = name
self.initials = initials
self.logoURL = logoURL
self.brandColor = brandColor
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
name = try values.decode(String.self, forKey: .name)
initials = try values.decode(String.self, forKey: .initials)
logoURL = try values.decode(URL.self, forKey: .logoURL)
brandColor = try values.decode(String.self, forKey: .brandColor)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .name)
try container.encode(initials, forKey: .initials)
try container.encode(logoURL, forKey: .logoURL)
try container.encode(brandColor, forKey: .brandColor)
}
}
Defaults struct to control storage
struct CompanyDefaults {
static private let companiesKey = "companiesKey"
static var companies: [String:Company] = {
guard let data = UserDefaults.standard.data(forKey: companiesKey) else { return [:] }
let companies = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? [String : Company] ?? [:]
return companies!
}() {
didSet {
guard let data = try? NSKeyedArchiver.archivedData(withRootObject: companies, requiringSecureCoding: false) else {
return
}
UserDefaults.standard.set(data, forKey: companiesKey)
}
}
}
I should be able to reference the stored dictionary throughout my code like CompanyDefaults.companies.count
For reference, a friend helped me do a similar task for an array of Account classes stored in user defaults. The code that works perfectly for that is below. The reason I tried a different way is that I had a different data structure (dictionary) and made the decision to use structs.
class Account: NSObject, NSCoding {
let service: String
var username: String
var password: String
func encode(with aCoder: NSCoder) {
aCoder.encode(service)
aCoder.encode(username)
aCoder.encode(password)
}
required init?(coder aDecoder: NSCoder) {
guard let service = aDecoder.decodeObject() as? String,
var username = aDecoder.decodeObject() as? String,
var password = aDecoder.decodeObject() as? String else {
return nil
}
self.service = service
self.username = username
self.password = password
}
init(service: String, username: String, password: String) {
self.service = service
self.username = username
self.password = password
}
}
struct Defaults {
static private let accountsKey = "accountsKey"
static var accounts: [Account] = {
guard let data = UserDefaults.standard.data(forKey: accountsKey) else { return [] }
let accounts = NSKeyedUnarchiver.unarchiveObject(with: data) as? [Account] ?? []
return accounts
}() {
didSet {
guard let data = try? NSKeyedArchiver.archivedData(withRootObject: accounts, requiringSecureCoding: false) else {
return
}
UserDefaults.standard.set(data, forKey: accountsKey)
}
}
}
You are mixing up NSCoding and Codable. The former requires a subclass of NSObject, the latter can encode the structs and classes directly with JSONEncoder or ProperListEncoder without any Keyedarchiver which also belongs to NSCoding.
Your struct can be reduced to
struct Company: Codable {
var name : String
var initials : String
var logoURL : URL?
var brandColor : String?
}
That's all, the CodingKeys and the other methods are synthesized. I would at least declare name and initials as non-optional.
To read and save the data is pretty straightforward. The corresponding CompanyDefaults struct is
struct CompanyDefaults {
static private let companiesKey = "companiesKey"
static var companies: [String:Company] = {
guard let data = UserDefaults.standard.data(forKey: companiesKey) else { return [:] }
return try? JSONDecoder.decode([String:Company].self, from: data) ?? [:]
}() {
didSet {
guard let data = try? JSONEncoder().encode(companies) else { return }
UserDefaults.standard.set(data, forKey: companiesKey)
}
}
}

How to implement Codable in a custom subclass (Swift 4) [duplicate]

Should the use of class inheritance break the Decodability of class. For example, the following code
class Server : Codable {
var id : Int?
}
class Development : Server {
var name : String?
var userId : Int?
}
var json = "{\"id\" : 1,\"name\" : \"Large Building Development\"}"
let jsonDecoder = JSONDecoder()
let item = try jsonDecoder.decode(Development.self, from:json.data(using: .utf8)!) as Development
print(item.id ?? "id is nil")
print(item.name ?? "name is nil") here
output is:
1
name is nil
Now if I reverse this, name decodes but id does not.
class Server {
var id : Int?
}
class Development : Server, Codable {
var name : String?
var userId : Int?
}
var json = "{\"id\" : 1,\"name\" : \"Large Building Development\"}"
let jsonDecoder = JSONDecoder()
let item = try jsonDecoder.decode(Development.self, from:json.data(using: .utf8)!) as Development
print(item.id ?? "id is nil")
print(item.name ?? "name is nil")
output is:
id is nil
Large Building Development
And you can't express Codable in both classes.
I believe in the case of inheritance you must implement Coding yourself. That is, you must specify CodingKeys and implement init(from:) and encode(to:) in both superclass and subclass. Per the WWDC video (around 49:28, pictured below), you must call super with the super encoder/decoder.
required init(from decoder: Decoder) throws {
// Get our container for this subclass' coding keys
let container = try decoder.container(keyedBy: CodingKeys.self)
myVar = try container.decode(MyType.self, forKey: .myVar)
// otherVar = ...
// Get superDecoder for superclass and call super.init(from:) with it
let superDecoder = try container.superDecoder()
try super.init(from: superDecoder)
}
The video seems to stop short of showing the encoding side (but it's container.superEncoder() for the encode(to:) side) but it works in much the same way in your encode(to:) implementation. I can confirm this works in this simple case (see playground code below).
I'm still struggling with some odd behavior myself with a much more complex model I'm converting from NSCoding, which has lots of newly-nested types (including struct and enum) that's exhibiting this unexpected nil behavior and "shouldn't be". Just be aware there may be edge cases that involve nested types.
Edit: Nested types seem to work fine in my test playground; I now suspect something wrong with self-referencing classes (think children of tree nodes) with a collection of itself that also contains instances of that class' various subclasses. A test of a simple self-referencing class decodes fine (that is, no subclasses) so I'm now focusing my efforts on why the subclasses case fails.
Update June 25 '17: I ended up filing a bug with Apple about this. rdar://32911973 - Unfortunately an encode/decode cycle of an array of Superclass that contains Subclass: Superclass elements will result in all elements in the array being decoded as Superclass (the subclass' init(from:) is never called, resulting in data loss or worse).
//: Fully-Implemented Inheritance
class FullSuper: Codable {
var id: UUID?
init() {}
private enum CodingKeys: String, CodingKey { case id }
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(UUID.self, forKey: .id)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(id, forKey: .id)
}
}
class FullSub: FullSuper {
var string: String?
private enum CodingKeys: String, CodingKey { case string }
override init() { super.init() }
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let superdecoder = try container.superDecoder()
try super.init(from: superdecoder)
string = try container.decode(String.self, forKey: .string)
}
override func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(string, forKey: .string)
let superencoder = container.superEncoder()
try super.encode(to: superencoder)
}
}
let fullSub = FullSub()
fullSub.id = UUID()
fullSub.string = "FullSub"
let fullEncoder = PropertyListEncoder()
let fullData = try fullEncoder.encode(fullSub)
let fullDecoder = PropertyListDecoder()
let fullSubDecoded: FullSub = try fullDecoder.decode(FullSub.self, from: fullData)
Both the super- and subclass properties are restored in fullSubDecoded.
Found This Link - Go down to inheritance section
override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(employeeID, forKey: .employeeID)
}
For Decoding I did this:
required init(from decoder: Decoder) throws {
try super.init(from: decoder)
let values = try decoder.container(keyedBy: CodingKeys.self)
total = try values.decode(Int.self, forKey: .total)
}
private enum CodingKeys: String, CodingKey
{
case total
}
🚀 Swift introduced Property Wrappers in 5.1 I implemented a library called SerializedSwift that uses the power of property wrappers to Decode and Encode JSON data to objects.
One of my main goals was, to make inherited object to decode out of the box, without additonal init(from decoder: Decoder) overrides.
import SerializedSwift
class User: Serializable {
#Serialized
var name: String
#Serialized("globalId")
var id: String?
#Serialized(alternateKey: "mobileNumber")
var phoneNumber: String?
#Serialized(default: 0)
var score: Int
required init() {}
}
// Inherited object
class PowerUser: User {
#Serialized
var powerName: String?
#Serialized(default: 0)
var credit: Int
}
It also supports custom coding keys, alternate keys, default values, custom transformation classes and many more features to be included in the future.
Available on GitHub (SerializedSwift).
I was able to make it work by making my base class and subclasses conform to Decodable instead of Codable. If I used Codable it would crash in odd ways, such as getting a EXC_BAD_ACCESS when accessing a field of the subclass, yet the debugger could display all the subclass values with no problem.
Additionally, passing the superDecoder to the base class in super.init() didn't work. I just passed the decoder from the subclass to the base class.
How about using the following way?
protocol Parent: Codable {
var inheritedProp: Int? {get set}
}
struct Child: Parent {
var inheritedProp: Int?
var title: String?
enum CodingKeys: String, CodingKey {
case inheritedProp = "inherited_prop"
case title = "short_title"
}
}
Additional info on composition: http://mikebuss.com/2016/01/10/interfaces-vs-inheritance/
Here is a library TypePreservingCodingAdapter to do just that (can be installed with Cocoapods or SwiftPackageManager).
The code below compiles and works just fine with Swift 4.2. Unfortunately for every subclass you'll need to implement encoding and decoding of properties on your own.
import TypePreservingCodingAdapter
import Foundation
// redeclared your types with initializers
class Server: Codable {
var id: Int?
init(id: Int?) {
self.id = id
}
}
class Development: Server {
var name: String?
var userId: Int?
private enum CodingKeys: String, CodingKey {
case name
case userId
}
init(id: Int?, name: String?, userId: Int?) {
self.name = name
self.userId = userId
super.init(id: id)
}
required init(from decoder: Decoder) throws {
try super.init(from: decoder)
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decodeIfPresent(String.self, forKey: .name)
userId = try container.decodeIfPresent(Int.self, forKey: .userId)
}
override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .name)
try container.encode(userId, forKey: .userId)
}
}
// create and adapter
let adapter = TypePreservingCodingAdapter()
let encoder = JSONEncoder()
let decoder = JSONDecoder()
// inject it into encoder and decoder
encoder.userInfo[.typePreservingAdapter] = adapter
decoder.userInfo[.typePreservingAdapter] = adapter
// register your types with adapter
adapter.register(type: Server.self).register(type: Development.self)
let server = Server(id: 1)
let development = Development(id: 2, name: "dev", userId: 42)
let servers: [Server] = [server, development]
// wrap specific object with Wrap helper object
let data = try! encoder.encode(servers.map { Wrap(wrapped: $0) })
// decode object back and unwrap them force casting to a common ancestor type
let decodedServers = try! decoder.decode([Wrap].self, from: data).map { $0.wrapped as! Server }
// check that decoded object are of correct types
print(decodedServers.first is Server) // prints true
print(decodedServers.last is Development) // prints true
Swift 5
The compiler synthesises decodable code only for a type that directly adopts Codable protocol so that you observe decoding for a single of your type in inheritance.
But you can try next generic approach with KeyValueCoding package (https://github.com/ikhvorost/KeyValueCoding) and this package provides access to all properties metadata and allows to get/set any property for pure swift types dynamically. The idea is to make a base Coding class which adopts KeyValueCoding and implements decoding of all available properties in init(from: Decoder):
class Coding: KeyValueCoding, Decodable {
typealias DecodeFunc = (KeyedDecodingContainer<_CodingKey>, _CodingKey) throws -> Any?
struct _CodingKey: CodingKey {
let stringValue: String
let intValue: Int?
init(stringValue: String) {
self.stringValue = stringValue
self.intValue = Int(stringValue)
}
init(intValue: Int) {
self.stringValue = "\(intValue)"
self.intValue = intValue
}
}
static func decodeType<T: Decodable>(_: T.Type) -> (type: T.Type, f: DecodeFunc) {
(T.self, { try $0.decode(T.self, forKey: $1) })
}
static var decodeTypes: [(Any.Type, DecodeFunc)] = [
decodeType(Int.self),
decodeType(Int?.self),
decodeType(String.self),
decodeType(String?.self),
// Other types to support...
]
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: _CodingKey.self)
try container.allKeys.forEach { codingKey in
let key = codingKey.stringValue
guard let property = (properties.first { $0.name == key }),
let item = (Self.decodeTypes.first { property.type == $0.0 })
else {
return
}
var this = self
this[key] = try item.1(container, codingKey)
}
}
}
It is important to provide all supported types to decode in decodeTypes variable.
How to use:
class Server: Coding {
var id: Int?
}
class Development : Server {
var name: String = ""
}
class User: Development {
var userId: Int = 0
}
func decode() {
let json = "{\"id\": 1, \"name\": \"Large Building Development\", \"userId\": 123}"
do {
let user = try JSONDecoder().decode(User.self, from:json.data(using: .utf8)!)
print(user.id, user.name, user.userId) // Optional(1) Large Building Development 123
}
catch {
print(error.localizedDescription)
}
}