2

Looking at the following code (playground ready).

I'm unable to append data to an unwrapped optional array from within an if let statement.

What's the best method to allow appending for an optional array?

class ValueTypeTest {
    var data: [Int]?

    func tryAppend() {
        if var unwrappedData = self.data {
            unwrappedData += [2, 3] // problem !
            self.data! += [4, 5]    // works
        } else {
            // Initialize paging and initial results
            self.data = [0, 1]
        }

    }
}

var v = ValueTypeTest()
v.data // nil
v.tryAppend()
v.data // [0, 1]
v.tryAppend()
v.data // expected: [0, 1, 2, 3, 4, 5] actual: [0, 1, 4, 5]
Maxim Veksler
  • 29,272
  • 38
  • 131
  • 151
  • It seems like your design is wrong. A `tryAppend()` operation which always succeeds seems to contradict the idea that the array is optional. I'm sure your example is a simplified one, and may not exhibit some details of your actual code, but in the example you provide an empty non-optional array seems obviously more appropriate than an optional one. – Crowman Mar 09 '16 at 23:57

2 Answers2

1

Because Array is a value type and will be copied when you do the if var operation. So you're not changing self.data but unwrappedData.

Try this:

self.data = (self.data ?? [0, 1]) + [2, 3, 4, 5]

This is what I mean.

func tryAppend() {
    if let unwrappedData = self.data {
        self.data = unwrappedData + [2, 3, 4, 5]
    } else {
        // Initialize paging and initial results
        self.data = [0, 1]
    }
}
J.Wang
  • 1,136
  • 6
  • 12
  • Thanks but assigning to self.data beats the purpose of the unwrapping. I agree it's a better syntax I just wonder if this is the recommended solution. – Maxim Veksler Mar 09 '16 at 22:33
  • 1
    @MaximVeksler Well, at least you can do `self.data = unwrappedData + [2, 3]`. This might better suit your purpose? If you think about it, this is pretty much what you can do when unwrapping a value type. – J.Wang Mar 09 '16 at 22:36
  • tend to agree. Please update your answer? I'll see if this makes sense and accept. – Maxim Veksler Mar 09 '16 at 22:38
  • @MaximVeksler Updated. – J.Wang Mar 09 '16 at 23:18
0

var unwrappedData declared inside the function tryAppend() is a local variable for that function.

The result pane at that line shows you the output containing: [0, 1, 2, 3] for unwrappedData.

Ivan Gritsenko
  • 4,166
  • 2
  • 20
  • 34
Ranjan
  • 1
  • 3