Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to define a custom subscripting array operator which makes array elements "spring into existence" if necessary

was it possible to add operator func to Swift class subscript method

var x = ["dkfkd", "dkff"]
x[2] ??=  "mmmm" // equal to x[2] = x[2] ?? "mmmm"
like image 591
ruandao Avatar asked Feb 09 '26 22:02

ruandao


1 Answers

This isn’t related to the subscript operator, but more a question of how to define a ??= operator. Which you can do, but it might not work quite the way you expect.

Here’s a possible implementation:

// first define the ??= operator
infix operator ??= { }

// then some pretty standard logic for an assignment
// version of ??
func ??=<T>(inout lhs: T?, rhs: T) {
    lhs = lhs ?? rhs
}

This compiles, and works as you might be expecting:

var i: Int? = 1

i ??= 2   // i unchanged

var j: Int? = nil

j ??= 2  // j is now Some(2)

It will also work in combination with subscripts:

var a: [Int?] = [1, nil]

a[1] ??= 2

a[1]  // is now Some(2)

I say this might not work completely as expected because of the types. a ?? b takes an optional a, and if it’s nil, returns a default of b. However it returns a non-optional value. That’s kinda the point of ??.

On the other hand, ??= cannot do this. Because the left-hand side is already determined to be optional, and an assignment operator cannot change the type only the value. So while it will substitute the value inside the optional in the case of nil, it won’t change the type to be non-optional.

PS the reason the ??= function compiles at all is because non-optional values (i.e. what you will get back from lhs ?? rhs) are implicitly upgraded to optional values if necessary, hence lhs ?? rhs, of type T, can be assigned to lhs, which is of type T?.

like image 113
Airspeed Velocity Avatar answered Feb 12 '26 15:02

Airspeed Velocity



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!