Adding elements to optional arrays in Swift

后端 未结 4 1901
攒了一身酷
攒了一身酷 2020-12-08 07:03

What is the proper way to append an element on the end of an optional array? Let\'s say I have an optional array, myArray, and I want to append \'99\' on the end. Append() d

4条回答
  •  情书的邮戳
    2020-12-08 07:50

    Instead of using append, try using array merge operator. Because the result is an optional use nil coalescing operator to assign one element array when initial array was nil.

    var myArray = [Int]?()
    
    myArray? += [99]
    myArray = myArray ?? [99]
    

    I tried to merge it into one line expression but unfortunately Swift doesn't like it

    myArray = (myArray? += [99]) ?? [99]
    

提交回复
热议问题