Search code examples
arraysswiftoption-typexcode6-beta6

Concatenating to an Optional Array with the "+=" operator


I'm trying to append multiple strings to an array. This code works as expected:

var myArray: [String] = []
myArray += ["dog", "cat"]

This gives me an error:

var myArray: [String]! = []
myArray += ["dog", "cat"] //error: '[String]!' is not identical to 'UInt8'

Is this a bug, or is concatenating to an optional Array not supposed to work?


Solution

  • myArray is an optional, and as such you have to explicitly unwrap it in order to make the append work:

    myArray! += ["dog", "cat"]
    

    That sounds counterintuitive, because the purpose of the implicitly unwrapped optional is to avoid manual unwrapping. However the documentation says that:

    An implicitly unwrapped optional is a normal optional behind the scenes, but can also be used like a nonoptional value, without the need to unwrap the optional value each time it is accessed

    My explanation is that, being the optional an enum under the hood, the += operator is applied to the enum and not to the actual type wrapped by the optional itself.