Array in object from data model comes nil

swift check if array contains nil
swift unwrap optional array
swift remove nil from array
swift array with nil values
compactmapvalues
remove null values from dictionary swift 4
swift reduce array of objects
swift filter array of objects

I have a model class called Coupon and it has an array of objects called Array! When I create an object from from Coupon class the array inside of this object comes nil and it gets an error. What am I doing wrong?

class Coupon {
    private var _date: String!
    private var _editor: String!
    private var _predictions: Array<Prediction>?

var date: String {
    get {
        return _date
    }
}

var editor: String {
    get {
        return _editor
    }
}

var predictions: Array<Prediction>? {
    get {
        return _predictions
    }
    set {
        self._predictions = predictions
    }
}
}

And the controller is as follows: c.predictions![0] gives nil error

let ref = DataService.ds.REF_COUPONS.queryOrdered(byChild: "date")
    ref.observe(.childAdded, with: { (snapshot) in

        if let couponDict = snapshot.value as? Dictionary<String, AnyObject> {
            let c_key = snapshot.key
            let c = Coupon(couponKey: c_key, couponData: couponDict)
            let childSnapShot = snapshot.childSnapshot(forPath: "predictions")
            if let snapshots = childSnapShot.children.allObjects as? [FIRDataSnapshot] {

                for snap in snapshots{

                    let p_key = snap.key
                    let p = Prediction(predictionKey: p_key, predictionData: snap.value as! Dictionary<String, AnyObject>)
                    self.predictions.append(p) 
                    c.predictions![0] = self.predictions[0] <--- ERROR LINE
                }
            }
            self.coupons.append(c)
        }
        self.couponsTableView.reloadData()
    })

Because it's value is nil by default. So predictions! will result in trying to unwrap an optional whose value is nil kind of error.

You should create new array there:

c.predictions = [self.predictions[0]]

Also there is no need for backing fields in swift. Your Coupon class can be reduced to:

class Coupon {
    private(set) var date: String!
    private(set) var editor: String!
    var predictions: Array<Prediction>?
}

private(set) means that the value can only be set within this class.

The definition line of predictions var predictions: Array<Prediction>? can be replaced to have default value of empty array:

class Coupon {
    private(set) var date: String!
    private(set) var editor: String!
    var predictions: [Prediction] = []
}

[Prediction] is same as Array<Prediction>

Once it has default value of empty array instead of creating new array you can safely append to it:

c.predictions.append(self.predictions[0])

Also note that your code c.predictions[0] = self.predictions[0] would work never even in this case because the array is defaulted to empty has not 0th element.

Mac Programming for Absolute Beginners, The NSArray is known as a static array because you can store data in the array once, but *myOtherArray; This simply creates a pointer to an array object. nil]; A second way to fill an array with data is to declare and initialize the array on a  Well, nil is a special Ruby object used to represent an “empty” or “default” value. It’s also a “falsy” value, meaning that it behaves like false when used in a conditional statement. Now: There is ONLY one nil object, with an object_id of 4 (or 8 in 64-bit Ruby), this is part of why nil is special. nil.object_id # 4 Let’s take


When you create the class Coupon with let c = Coupon(couponKey: c_key, couponData: couponDict) your array is not initialize, so that's normal to have an error when you are trying to use it in the line c.predictions![0] = self.predictions[0] <--- ERROR LINE, your object Coupon you could initialize the array predictions as an empty array like this

class Coupon {
private var _date: String!
private var _editor: String!
private var _predictions = [Prediction]()

Explorations in Computing: An Introduction to Computer Science, Ruby arrays are collections of objects, and we can store any type of data in an array contains the special object nil, which stands for “nothing” or “no object,” so  The problem with empty? is that you need to know the class of the object to be sure you won’t get an exception. If you don’t know if an object is an Array or nil then using empty? alone is not safe. You need tedious double protection.


Element in predictions array at index 0 doesn't exist, so you can't replace it with new element. I suggest you to replace _predictions array with empty predictions array

var predictions = [Prediction]()

then you can append new element to this array like this:

c.predictions.append(self.predictions[0])

Also in your case there is no need to use property with getter and setter and you can also use struct instead of class

struct Coupon {
    var date: String
    var editor: String
    var predictions = [Prediction]()

    // your convenience init
}

How to filter nil values out of the collection types— Swift, Our goal is to filter non-nil elements from optionalElements array and build a dictionary from user payment data which is contain non-nil value and use properties when building a dictionary object — First idea to to assign  NSArray and its subclass NSMutable Array manage ordered collections of objects called arrays. NSArray creates static arrays, and NSMutable Array creates dynamic arrays. You can use arrays when you need an ordered collection of objects. NSArray is “toll-free bridged” with its Core Foundation counterpart, CFArray.


Beginning iPhone Development with Swift: Exploring the iOS SDK, nil let objects = context?.executeFetchRequest(request, error:&error) if (objects! == nil) objects from the persistent store and return them in an optional array. Select Core_Data_Persistence.xcdatamodel to open Xcode's data model editor. In this case, the values stored in the array are references to objects that live outside the array. If you change a reference to an object in one array, only that array has a reference to the new object. However, if two arrays contain references to the same object, you can observe changes to that object’s properties from both arrays. For example:


Beginning iOS Apps with Facebook and Twitter APIs: for iPhone, , When it comes time to fetch the Tweets from our Core Data model, we use the Core NSFetchRequest takes an entity description (Tweet, in this case) and a managed object context. The array of Tweets is then returned from the method. of the id attribute of the Tweets: - (NSArray*)tweets { NSMutableArray *tweets = nil;  We use an object array to store different types of data in each element location. An object array can store reference types such as string and value types such as int.Int, uint. Tip: For each object element, the type information is retained and can be used later. It is not lost. Allocate: We allocate an object array on the managed heap


Adding data | Firestore, Firestore lets you write a variety of data types inside a document, including strings, booleans, numbers, dates, null, and nested arrays and objects. Firestore always  It either returns an NSArray object with zero or more objects, or it returns nil. If nil is returned, you have received an error from Core Data and need to respond to it. If the array exists, you receive possible results for the request even though the NSArray may be empty. An empty NSArray indicates that there were no records found.