Set capacity to array of model in Decodable protocol - ios

I want to set a model array max capacity if the user has not logged in even JSON response contains more records.
public class AlertsInbox: Codable {
public var messages: [Messages]?
public init(messages: [Messages]) {
self.messages = messages
if !GlobalVar.isLoggedIn,
let capacity = GlobalVar.messageCapacity {
self.messages?.reserveCapacity(capacity)
}
}
}
Decode json response:
let responseMessage = try JSONDecoder().decode(AlertsInbox.self, from: data)
Using reserveCapacity in init of model but it gets overridden with the number of records received in response.
How to restrict while decoding?
Thanks

You should not conditionally strip/drop out elements from an array in the Type's initializer. This consideration is against the responsibility role of Model object. Instead it's a job for the controller object.
But you can have an access point in the model type. Let's say, you have a property messages in your AlertsInbox object. You can have another access point with another property, let's say, limitedMessages that will be a computed property.
Look at the below code. I intentionally changed the type's semantics from Class to Struct. But you are free to use as your need.
struct AlertsInbox: Codable {
let messages: [Message]
var limitedMessages: [Message] {
// here you will use the value of your limit
// if the limit exceeds the size of the array, whole array will be returned
return Array(messages.prefix(5))
}
struct Message: Codable {
let title: String
}
}
Now you will use this, just like any other property, when you need the stripped out version of your actual messages. Like alertInbox.limitedMessages instead of the messages property.
But if you are not satisfied with the above and wanna stick to your plan, you can do that as well. See:
struct AlertsInbox: Codable {
let messages: [Message]
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let messages = try container.decode([Message].self, forKey: .messages)
// the idea of limiting the element numbers is same as the above
self.messages = Array(messages.prefix(5))
}
struct Message: Codable {
let title: String
}
}

Related

If something conforms to Codable can it EVER fail to be Encoded or Decoded?

I was wondering if an object which conforms to Codable can ever cause an error while in the process of being encoded or decoded. I feel as though conforming to the protocol ensures that an error can never be thrown.
For example if I have a struct called Book:
struct Book: Codable, Identifiable {
#DocumentID var id: String?
var name: String
}
Can this struct ever fail to be encoded or decoded?
For example if I do:
try! docRef.setData(from: book) { error in _ }
I don't think this can ever throw an error synchronously if Book conforms to Codable.
Similarly,
try! docRef.data(as: Book.self)
should never throw because, again, Book conforms to Codable
If I'm wrong and Book may fail while being Encoded or Decoded please explain under what conditions/circumstances that might happen.
Thanks in advance!
Encoding:
For JSONEncoder the cases where encoding fails are documented here: https://developer.apple.com/documentation/foundation/jsonencoder/2895034-encode.
Afaik assuming all properties and contained data structures are composed of simple types like Int, String, Array, Dictionary it will never fail because these values can be always represented as JSON. But you might have a type like Float that throws an Error when the value cannot be represented as JSON.
Decoding:
Any invalid JSON input like missing fields or syntax errors will throw an error. I recommend always handling these and making sure they don't go unnoticed / the user gets at least a "sorry, something went wrong, we're looking into it" experience.
As you asked this question in the context of Firestore, I'd like to add some more details in addition to what Ralf mentioned in his answer.
When decoding a Firestore document, there are a number of situations that might in a mapping error, which is why you should be prepared to handle them.
For example:
Your struct might expect a field (i.e. it is non-optional), but the field is missing in the Firestore document. This might happen when you've got other apps (Android, web, or even a previous version of your iOS app) that write to the same document, but use a previous version of the schema
One (or more) of the attributes on the document might have a different data type than your struct.
The following code snippet contains extensive error handling for these and other cases (please be aware that you need to adjust how to handle those errors to your individual situation - you might or might not want to display a user-visible error message, for example). The code is taken from my article Mapping Firestore Data in Swift - The Comprehensive Guide.
class MappingSimpleTypesViewModel: ObservableObject {
#Published var book: Book = .empty
#Published var errorMessage: String?
private var db = Firestore.firestore()
func fetchAndMap() {
fetchBook(documentId: "hitchhiker")
}
func fetchAndMapNonExisting() {
fetchBook(documentId: "does-not-exist")
}
func fetchAndTryMappingInvalidData() {
fetchBook(documentId: "invalid-data")
}
private func fetchBook(documentId: String) {
let docRef = db.collection("books").document(documentId)
docRef.getDocument { document, error in
if let error = error as NSError? {
self.errorMessage = "Error getting document: \(error.localizedDescription)"
}
else {
let result = Result { try document?.data(as: Book.self) }
switch result {
case .success(let book):
if let book = book {
// A Book value was successfully initialized from the DocumentSnapshot.
self.book = book
self.errorMessage = nil
}
else {
// A nil value was successfully initialized from the DocumentSnapshot,
// or the DocumentSnapshot was nil.
self.errorMessage = "Document doesn't exist."
}
case .failure(let error):
// A Book value could not be initialized from the DocumentSnapshot.
switch error {
case DecodingError.typeMismatch(let type, let context):
self.errorMessage = "\(error.localizedDescription): \(context.debugDescription)"
case DecodingError.valueNotFound(let type, let context):
self.errorMessage = "\(error.localizedDescription): \(context.debugDescription)"
case DecodingError.keyNotFound(let key, let context):
self.errorMessage = "\(error.localizedDescription): \(context.debugDescription)"
case DecodingError.dataCorrupted(let key):
self.errorMessage = "\(error.localizedDescription): \(key)"
default:
self.errorMessage = "Error decoding document: \(error.localizedDescription)"
}
}
}
}
}
}
If you're curious about how Firestore implements the Codable protocol, head over to the source code. For example, searching for DecodableError will show how exactly which error conditions might occur, and why.

How to add a description to a Data instance in Swift

I wanted to add a description to my Data instances so I know what they're meant to be used for.
Eg: "This data is for (user.name)'s profile picture" or "This data is a encoded User instance" etc.
I was going through the properties available to Data instances and saw there was a description and debugDescription property. I tried to set the values for those properties but it seems like I can't since they are get-only properties. Is there any other way to add a description to a Data instance?
Edit:
Wrapping a Data instance as recommended below is a great solution but if there's a way to achieve the same without using a wrapper please let me know.
You can create a light-weight wrapper like following -
import Foundation
struct DescriptiveData: CustomStringConvertible, CustomDebugStringConvertible {
let data: Data
let customDescription: String?
init(data: Data, customDescription: String? = nil) {
self.data = data
self.customDescription = customDescription
}
var description: String { customDescription ?? data.description }
var debugDescription: String { description }
}
Usage
let data = DescriptiveData(data: Data(), customDescription: "data for profile picture")
print(data)
// data for profile picture

How to replace/update dictionary in Array of Dictionary based on Type

I'm getting below JSON response from server, and displaying phone number on screen.
Now user can change/update any of phone number, so we have to update particular mobile number in same object and send it to server.
"phone_numbers": [
{
"type": "MOBILE",
"number": "8091212121"
},
{
"type": "HOME",
"number": "4161212943"
},
{
"type": "BUSINESS",
"number": "8091212344"
}
]
My model class is looks like this:
public struct Contact: Decodable {
public let phone_numbers: [Phone]?
}
public struct Phone: Decodable {
public let type: PhoneType?
public let number: String?
}
I'm struggling to update this JSON object for particular phone number.
For example, if I want to update BUSINESS number only in above array, What's best way to do it.
I'm using XCode 11 and Swift 5.
Because all your properties are defined as constants (let), nothing can be updated. You have to initialize and return a new Contact object with the updated phone numbers.
If you change the properties to var, then you can update:
public enum PhoneType: String, Decodable {
case mobile = "MOBILE"
case home = "HOME"
case business = "BUSINESS"
}
public struct Contact: Decodable {
public var phone_numbers: [Phone]?
mutating func update(phoneNumber: String, for type: PhoneType) {
guard let phone_numbers = self.phone_numbers else { return }
for (i, number) in phone_numbers.enumerated() {
if number.type == type {
self.phone_numbers![i].number = phoneNumber
}
}
}
}
public struct Phone: Decodable {
public var type: PhoneType?
public var number: String?
}
var contact = try! JSONDecoder().decode(Contact.self, from: jsonData)
contact.update(phoneNumber: "123456", for: .business)
I'm struggling to update this JSON object for particular phone number.
It shouldn't be a JSON object when you update it. Think of JSON as just a format for transferring data. Once transferred, you should parse it into something that you can work with, like an array of dictionaries or whatever. If you've done that, then more specific questions you might ask are:
How can I find a specific entry in an array?
How can I modify the fields of a struct?
How can I replace one entry in an array with another?
After looking at the definitions of your structures, I think the problem you're having probably has to do with how you've declared them:
public struct Phone: Decodable {
public let type: PhoneType?
public let number: String?
}
Because you used let to declare type and number, those fields cannot be changed after initialization. If you want the fields of a Phone struct to be modifiable, you need to declare them with var instead of let.
The same thing is true for your Contact struct:
public struct Contact: Decodable {
public let phone_numbers: [Phone]?
}
You've declared phone_numbers as an immutable array because you used let instead of var. If you want to be able to add, remove, or modify the array in phone_numbers, you need to use var instead.
The struct declarations you have right now work fine for reading the data from JSON because all the components of the JSON data are constructed using the values from the JSON. But again, you'll need to make those structs modifiable by switching to var declarations if you want to be able to make changes.
There are a couple of ways to approach this (I'm assuming PhoneType is an enum you have somewhere)
You can iterate over the array and guard for only business numbers, like so
for phone in phone_numbers{
guard phone.type == .MOBILE else { continue }
// Code that modifies phone
}
You can filter and iterate over the array, like so
phone_numbers.filter {$0.type == .BUSINESS }.forEach { phone in
// Modify phone here
}
You can then modify the right value in the array with it's index, like this
for (phoneIndex, phone) in phone_numbers.enumerated() {
guard phone.type == .BUSINESS else { continue }
phone_numbers[phoneIndex].type = ANOTHER_TYPE
}
Some can argue that the second is preferred over the first, because it is an higher order function, but in my day to day activities, I tend to use both and believe that this is a matter of taste

How would one create a List<AnyRealmObject> in Swift?

OK, first, I know that there is no such thing as AnyRealmObject.
But I have a need to have something the behaves just like a Realm List, with the exception that any kind of Realm Object can be added to the list -- they don't all have to be the same type.
Currently, I have something like this:
enter code here
class Family: Object {
var pets: List<Pet>
}
class Pet: Object {
var dog: Dog?
var cat: Cat?
var rabbit: Rabbit?
}
Currently, if I wanted to add in, say, Bird, I'd have to modify the Pet object. I don't want to keep modifying that class.
What I really want to do is this:
class Family: Object {
var pets: List<Object>
}
Or, maybe, define a Pet protocol, that must be an Object, and have var pets: List<Pet>
The point is, I want a databag that can contain any Realm Object that I pass into it. The only requirement for the databag is that the objects must be Realm Objects.
Now, since Realm doesn't allow for this, how could I do this, anyway? I was thinking of creating something like a Realm ObjectReference class:
class ObjectReference: Object {
var className: String
var primaryKeyValue: String
public init(with object: Object) {
className = ???
primaryKeyValue = ???
}
public func object() -> Object? {
guard let realm = realm else { return nil }
var type = ???
var primaryKey: AnyObject = ???
return realm.object(ofType: type, forPrimaryKey: primaryKey)(
}
}
The stuff with the ??? is what I'm asking about. If there's a better way of doing this I'm all ears. I think my approach is ok, I just don't know how to fill in the blanks, here.
(I'm assuming that you are writing an application, and that the context of the code samples and problem you provided is in terms of application code, not creating a library.)
Your approach seems to be a decent one given Realm's current limitations; I can't think of anything better off the top of my head. You can use NSClassFromString() to turn your className string into a Swift metaclass object you can use with the object(ofType:...) API:
public func object() -> Object? {
let applicationName = // (application name goes here)
guard let realm = realm else { return nil }
guard let type = NSClassFromString("\(applicationName).\(className)") as? Object.Type else {
print("Error: \(className) isn't the name of a Realm class.")
return nil
}
var primaryKey: String = primaryKeyValue
return realm.object(ofType: type, forPrimaryKey: primaryKey)(
}
My recommendation is that you keep things simple and use strings exclusively as primary keys. If you really need to be able to use arbitrary types as primary keys you can take a look at our dynamic API for ideas as to how to extract the primary key value for a given object. (Note that although this API is technically a public API we don't generally offer support for it nor do we encourage its use except when the typed APIs are inadequate.)
In the future, we hope to offer enhanced support for subclassing and polymorphism. Depending on how this feature is designed, it might allow us to introduce APIs to allow subclasses of a parent object type to be inserted into a list (although that poses its own problems).
This may not be a complete answer but could provide some direction. If I am reading the question correctly (with comments) the objective is to have a more generic object that can be the base class for other objects.
While that's not directly doable - i.e. An NSObject is the base for NSView, NSString etc, how about this...
Let's define some Realm objects
class BookClass: Object {
#objc dynamic var author = ""
}
class CardClass: Object {
#objc dynamic var team = ""
}
class MugClass: Object {
#objc dynamic var liters = ""
}
and then a base realm object called Inventory Item Class that will represent them
class InvItemClass: Object {
#objc dynamic var name = ""
#objc dynamic var image = ""
#objc dynamic var itemType = ""
#objc dynamic var book: BookClass?
#objc dynamic var mug: MugClass?
#objc dynamic var card: CardClass?
}
then assume we want to store some books along with our mugs and cards (from the comments)
let book2001 = BookClass()
book2001.author = "Clarke"
let bookIRobot = BookClass()
bookIRobot.author = "Asimov"
let item0 = InvItemClass()
item0.name = "2001: A Space Odyssey"
item0.image = "Pic of Hal"
item0.itemType = "Book"
item0.book = book2001
let item1 = InvItemClass()
item1.name = "I, Robot"
item1.image = "Robot image"
item1.itemType = "Book"
item1.book = bookIRobot
do {
let realm = try Realm()
try! realm.write {
realm.add(item0)
realm.add(item1)
}
} catch let error as NSError {
print(error.localizedDescription)
}
From here, we can load all of the Inventory Item Objects as one set of objects (per the question) and take action depending on their type; for example, if want to load all items and print out just the ones that are books.
do {
let realm = try Realm()
let items = realm.objects(InvItemClass.self)
for item in items {
switch item.itemType {
case "Book":
let book = item.book
print(book?.author as! String)
case "Mug":
return
default:
return
}
}
} catch let error as NSError {
print(error.localizedDescription)
}
As it stands there isn't a generic 'one realm object fits all' solution, but this answer provides some level of generic-ness where a lot of different object types could be accessed via one main base object.

Swift 4 Codable: Cannot exclude a property

I'm developing a simple music sequencer app. This kind of app tends to have a complex data structure which has to be saved/loaded, so the introduction of Codable protocol in Swift4 is totally a good news for me.
My problem is this:
I have to have a non-Codable property. It doesn't have to be coded because it's a temporary variable only kept alive while the app is active.
So I've just tried to exclude by implementing CodingKey, but the compiler still give me the error "Type 'Song' does not conform to protocol 'Decodable'".
Specifically I want to exclude "musicSequence" in the code below.
class Song : Codable { //Type 'Song' does not conform to protocol 'Decodable'
var songName : String = "";
var tempo : Double = 120;
// Musical structure
var tracks : [Track] = [] // "Track" is my custom class, which conforms Codable as well
// Tones
var tones = [Int : ToneSettings] (); // ToneSettings is also my custom Codable class
var musicSequence : MusicSequence? = nil; // I get the error because of this line
private enum CodingKeys: String, CodingKey {
case songName
case tempo
case tracks
case tones
}
func createMIDISequence () {
// Create MIDI sequence based on "tracks" above
// and keep it as instance variable "musicSequence"
}
}
Does anybody have any ideas?
(See below for a strange turn of events.)
Your use of CodingKeys is already taking care of you encoding. You still get that for free. But you'll need to tell the system how to handle decoding by hand:
required init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
songName = try values.decode(String.self, forKey: .songName)
tempo = try values.decode(Double.self, forKey: .tempo)
tracks = try values.decode([Track].self, forKey: .tracks)
tones = try values.decode([Int: ToneSettings].self, forKey: .tones)
}
It's not quite smart enough to figure out that musicSequence can and should default to nil (and maybe that would be too smart anyway).
It's probably worth opening a defect at bugs.swift.org to ask for this Decodable to be automatic. It should be able to figure it out in cases where you provide CodingKeys and there is a default value.
EDIT: When I first answered this, I exactly duplicated your error. But when I tried to do it again, copying your code fresh, the error doesn't show up. The following code compiles and runs in a playground:
import Foundation
struct Track: Codable {}
struct ToneSettings: Codable {}
struct MusicSequence {}
class Song : Codable { //Type 'Song' does not conform to protocol 'Decodable'
var songName : String = "";
var tempo : Double = 120;
// Musical structure
var tracks : [Track] = [] // "Track" is my custom class, which conforms Codable as well
// Tones
var tones = [Int : ToneSettings] (); // ToneSettings is also my custom Codable class
var musicSequence : MusicSequence? = nil; // I get the error because of this line
private enum CodingKeys: String, CodingKey {
case songName
case tempo
case tracks
case tones
}
func createMIDISequence () {
// Create MIDI sequence based on "tracks" above
// and keep it as instance variable "musicSequence"
}
}
let song = Song()
let data = try JSONEncoder().encode(song)
String(data: data, encoding: .utf8)
let song2 = try JSONDecoder().decode(Song.self, from: data)
I'm wondering if there's a compiler bug here; make sure to test this with the new beta.

Resources