What's the best way to mutate an optional of Array?

var list: [Int]? = [1, 2, 3]

// what's the best way to mutate list?

// this doesn't work:
if var x = list {
    x.append(123)
}
print(list ?? "list is nil")     // Optional([1, 2, 3])

// this work, but is there better way?
if let _ = list {
    list?.append(44)
    list!.append(44444)
}

print(list ?? "list is nil")     // Optional([1, 2, 3, 44, 44444])
list?.append(123)

(There's no need for any check, since optional chaining will make it do nothing if it's nil.)

4 Likes
Terms of Service

Privacy Policy

Cookie Policy