Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a infix custom operator that handles optionality in swift

Tags:

xcode

ios

swift

I'm trying to implement a custom operator for Collections similar to the Elvis operator (?: in kotlin, ?? in swift), but in addition to checking nullability, the operator also checks if the collection is Empty.

However, when I try to use the operator, the code doesn't compile. The compiler throws an "ambiguous use of operator" error.

The implementation of the ?? operator in the swift language seems to be really similar to mine, so I'm a little lost.. Any help to understand why this happens, and how to fix it, will be greatly appreciated.


/// Returns the first argument if it's not null and not empty, otherwise will return the second argument.
infix operator ?/ : NilCoalescingPrecedence

@inlinable func ?/ <T: Collection>(optional: T?, defaultValue: @autoclosure () throws -> T) rethrows -> T {
    if let value = optional,
       !value.isEmpty {
        return value
    } else {
        return try defaultValue()
    }
}

@inlinable func ?/ <T: Collection>(optional: T?, defaultValue: @autoclosure () throws -> T?) rethrows -> T? {
    if let value = optional,
       !value.isEmpty {
        return value
    } else {
        return try defaultValue()
    }
}

func test() {
    let optionalValue: String? = nil
    
    let value1: String = optionalValue ?? "default value" // This works
    let value2: String = optionalValue ?/ "default value" // This works
    let value3: String? = optionalValue ?/ nil // This works
    let value4: String? = optionalValue ?? nil // This works
    let value5: String? = optionalValue ?? "default value" // This works
    let value6: String? = optionalValue ?/ "default value" // This dont compile: Ambiguous use of operator '?/'
}

The standard implementation for the ?? operator can be found at: https://github.com/apple/swift/blob/main/stdlib/public/core/Optional.swift, just search for "?? <" in the browser.

Maybe I'm using the wrong approach to solve this problem. If anyone knows a better solution will be great too.

like image 444
jXavier Avatar asked Oct 14 '25 11:10

jXavier


2 Answers

Short answer, you can't do that. Probably ??, provided by swift, works because swift has it's own powers and it treats these situations on it's own. But for our code, it doesn't work like that.

What will happen there is:

For the expression: let value2: String = optionalValue ?/ "default value".

  • First the compiler will look to the optionalValue parameter and will find 2 methods that accept an optional as first parameter;
  • Then it will look to the second parameter (defaultValue) that is a closure returning a non-optional T: Collection instance, and it will filter and match the first operator overload;
  • The last thing is the return value that is a non-optional T: Collection instance, and the first method is complient;
  • Success;

For the expression: let value4: String? = optionalValue ?/ "default value".

  • First the compiler will look to the optionalValue parameter and will find 2 methods that accept an optional as first parameter;
  • Then it will look to the second parameter (defaultValue) that is a closure returning an optional T: Collection aka Optional<T> where T: Collection instance, and then it will find 2 options for the 2 parameters so far;
  • At this point it will look for the return type of the function, but it will fail too;
  • Compiler error;

The reason that it fails is that T: Collection in your code is translated to String. And for the defaultValue return type an non-optional String fits the first and second methods, leading the compiler to be unsure which one it should use.

let string: String? = "value" and let string: String? = Optional<String>.init("value") are the same thing for the compiler due to implicit conversions that Swift does.

So there is not way to make this work from where my knowledge stands right now.

like image 121
Anderson Lucas C. Ramos Avatar answered Oct 17 '25 03:10

Anderson Lucas C. Ramos


It turns out that swift has an attribute called @_disfavoredOverload, when I use it on the second method, everything works as intended.

Now the implementation of the second method is:

@_disfavoredOverload
@inlinable func ?/ <T: Collection>(optional: T?, defaultValue: @autoclosure () throws -> T?) rethrows -> T? {
    if let value = optional,
       !value.isEmpty {
        return value
    } else {
        return try defaultValue()
    }
}

Discovered this on the swift forum: https://forums.swift.org/t/how-to-implement-a-infix-custom-operator-that-handles-optionality-in-swift/47260/3

like image 45
jXavier Avatar answered Oct 17 '25 04:10

jXavier



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!