Mutating an Optional-wrapped value type

If I want to mutate a value that’s within an Optional, I’d have to use an if-var or similar, mutate that copy, then copy it back? I did find out that mutating instance methods can work through a myVariable?.selfMutatingMethod.

I'm not sure what exactly you want to do. For what it's worth, you can use someOptional? as an L-value and mutate that, like this:

var x: Int? = 1
x? += 100 // Note the question mark
print(x) // Optional(101)

The behavior is equivalent to a mutating method such as x?.add(100). If x had been .none, line 2 would have had no effect, and x would still be .none in line 3.

6 Likes

Optional also has the map and flatMap operators that you can use to unwrap, mutate, and return an optional value.

To follow with @ole ‘s example:

var x: Int? = 1
x = x.map { unwrapped in
    unwrapped + 100
}
// Or, more concisely:
// x = x.map { $0 + 100 }

print(100) // Optional(101)
1 Like

Optional chaining is better in this case because it's in-place modification and works with noncopyable optional.