porkchopbento
porkchopbento

Reputation: 75

What's the difference between someArray: [Int]? vs someArray: [Int] = [Int]()

I've been trying to work on some project with JSON data and I had encountered a problem where when I declare my array someArray: [Int]? the printed data were all nils. However, the moment I changed to someArray:[Int] = [Int](), all the data from the JSON data appended into the array.

So can any of you Swift gurus tell me why does something like this happen and what's the difference between the former and latter version besides one in an optional?

Upvotes: 1

Views: 356

Answers (3)

Mukul More
Mukul More

Reputation: 564

Swift has it own features and Optional values are one of them. Once you declare a variable or constant saying

var sampleVariable: [Int]?

What you do is create a variable to initialize or allocate a memory to it. After you append value or assign values to the variable, then it can have an existence on the memory. Make sure you use if let block before using optional variables

Similarly for

var sampleVariable = [Int]()

Here you have assigned allocated and initialized the variable. It can never be nil. You can go ahead an assign append values to it.

Upvotes: 0

Malik
Malik

Reputation: 3802

someArray: [Int]? is just a declaration not an initialisation. The ? symbol suggests that it is an optional value which can be nil.

someArray: [Int] = [Int]() is a declaration as well as an initialisation so you get the values appended.

You can also do it on seperate lines like this

someArray: [Int]?
someArray = [Int]()

Upvotes: 4

rob mayoff
rob mayoff

Reputation: 385500

whats the difference between the former and later version besides one in an optional?

There is no other difference, but that's all the difference that matters.

I guess when you tried [Int]?, your code looked something like this:

class myObject {
    var someArray: [Int]?

    func add(_ x: Int) {
        someArray?.append(x)
    }
}

And then when you called add(x), and checked someArray after, someArray was still nil. The ? in someArray?.append(x) is called “optional chaining”, and it means “if someArray is nil, do nothing. Otherwise, call someArray!.append(x)”. Since you never set someArray to non-nil, it always does nothing.

Then I guess you tried something like this:

class myObject {
    var someArray: [Int] = [Int]()

    func add(_ x: Int) {
        someArray.append(x)
    }
}

In this case, someArray is not an optional. It is initialized to an empty array. It can be any array of Int, but it is never nil. Since it's not optional, there's no optional chaining going on, so there's no ? in someArray.append(x) here.

If you want to use an optional array, you need to set it non-nil at some point. Perhaps this is what you want:

class myObject {
    var someArray: [Int]?

    func add(_ x: Int) {
        if someArray == nil { someArray = [] }
        someArray!.append(x)
    }
}

Upvotes: 2

Related Questions