ikevin8me
ikevin8me

Reputation: 4313

Check if array is nil / or has been loaded in Swift / iOS?

What is the best practice to check if an array of objects has been loaded in Swift?

Say, if I declare an array in a class, and it is lazily loaded. Apple's docs say the array declaration / initialization is something like

var events = [Event]()

I suppose the above means the array is already initialized (ie. not nil).

Then, I need a function like:

func getEvents() -> [Event] {
    // check if array is nil, and if so, load the events (not: which could be 0 events)
    return events
}

In Java, I would declare something like

ArrayList<Event> events;

public ArrayList<Event> getEvents() {
   if(!events) { // null means never been loaded
       events = new ArrayList<Event>();
       events = loadEvents(); // load the events, which could be zero
   }
}

What is the best practice to code the equivalent in Swift?

Upvotes: 1

Views: 2322

Answers (2)

Luca Angeletti
Luca Angeletti

Reputation: 59526

Lazy Stored Property

In Swift you can declare a lazy stored property: it does exactly what you need.

struct Event { }

class Foo {
    lazy var events: [Event] = { self.loadEvents() }()

    private func loadEvents() -> [Event] {
        print("Loading events")
        return [Event(), Event(), Event()]
    }
}

We associated a closure to the events property. The closure defines how the events property should be populated and will be executed only when the property is used.

let foo = Foo()
print(foo.events) // now the events property is populated

enter image description here

Upvotes: 7

Diego
Diego

Reputation: 2415

You may experience an Array in these ways:

var vect = [String]()
 if vect.isEmpty {
    print ("true")
 }else{
    print("false")
 }

Or

func ceck()->Void{
    guard !vect.isEmpty else{
       print ("true")
       return // return, break, or another logic this is example
    }
}

Upvotes: 1

Related Questions