Westerndays
Westerndays

Reputation: 13

Bypassing code on initial run

In my code I need to retrieve a saved array of data to populate student history data. I am using the following line of code - which works great.

returnedArray = UserDefaults.standard().object(forKey: "studentHistoryArray")! as! NSArray as! [[String]]

The problem I have is on the initial (first) run of the program. The array hasn't been created/saved yet so I need to skip this step, but only on the initial run of the program. Is there a way to run this line of code only on the first run of a program?

Upvotes: 0

Views: 35

Answers (1)

NRitH
NRitH

Reputation: 13903

var defaults = UserDefaults.standard()
let studentHistoryArrayKey = "studentHistoryArray"
var returnedArray = defaults.object(forKey: studentHistoryArrayKey) as? [[String]]
// I don't think that you need to use the intermediary cast to NSArray, but
// I could be wrong.

if returnedArray == nil {
    returnedArray = [[String]]()
    defaults.setObject(returnedArray, forKey: studentHistoryArrayKey)
}

// Now it's guaranteed to be non-nil, so do whatever you need to do with the array.

As a rule of thumb, if you're using ! as liberally as in your example, something's going to break.

Upvotes: 1

Related Questions