Check if an array exists Swift

In Objective-C I would write:

@property (nonatomic, strong) NSMutableArray *privateArray;
if (!self.privateArray) {
    // Populate the privateArray
}

Which checks that an array does not already exists before populating it. How could this be achieved in Swift? I have tried implementing it by translating my Obj-C code but am given an Xcode error "Unary operator '!' can not be applied to an operand of type '[AnyObject]'"

Swift attempt:

private var privateArray: [AnyObject]?

if !privateArray {
    // Populate the array
}

How would I check if the array exists before populating the array, in Swift? Is it just as simple to use .isEmpty on the array?

Thanks in advance!

Answers


In Objective-C this is called lazy loading. You declare a property but only create the property the first time it is accessed.

The trap you have fallen into is thinking that Swift is just a different syntax around Objective-C.

In Swift you can have a lazy var...

You can declare it like this...

@lazy var someArray: [String] = {
    return ["Hello", "World"]
}

This will do what you want.

As a side note. It's generally not a good idea to use AnyObject especially if you know the type of object the array will contain.

Also, by using this method you don't need the array to be optional and so can avoid the whole unwrapping thing.

You can read more about lazy properties by googling it. I found this and it looks quite good... http://mikebuss.com/2014/06/22/lazy-initialization-swift/


You should write:

if (privateArray == nil) {
    // Populate the array
}

Need Your Help

Password protect an entire directory with PHP authentication

php mysql authentication .htaccess passwords

I want to password protect an entire directory and authenticate users though a MySQL database using PHP. I know you can password protect directories using .htaccess but I can't seem to find out how...

Interoperability between Weblogic 10.3.1 and Oracle BPM 10.3.1

oracle migration weblogic-10.x bpm ora-17004

Im migrating an ALBPM 6.5 running on a WLS 10.0 to an Oracle BPM 10.3.1 running on WLS 10.3.1