Adding elements to optional arrays in Swift

后端 未结 4 1900
攒了一身酷
攒了一身酷 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:33

    @MartinR's answer is the correct answer, however, just for completeness's sake, if you have an optional and want to do different actions depending on whether it's nor or not you can just check if it's nil (or not nil):

    if myArray != nil {
        myArray?.append(99)
    } else {
        myArray = [99]
    }
    

    Note that (as you have probably figured out) optional binding doesn't work in your case because the array is a value type: it would create a copy of the array, and append a new element to it, without actually affecting the original array:

    // Wrong implementation - the new item is appended to a copy of myArray
    if var myArray = myArray {
        myArray.append(99)
    } else {
        myArray = [99]
    }
    

提交回复
热议问题