# Elvis Operator?

**URL:** <https://forums.swift.org/t/elvis-operator/11368>\
**Category:** Discussion\
**Created:** [March 25, 2018, 11:29pm UTC](https://forums.swift.org/t/elvis-operator/11368 "2018-03-25T23:29:55Z")\
**Posts on this page:** 15\
**Page:** 1

<div class="post-metadata">

**Author:** ![valleyman86](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/valleyman86/32/3041_2.png) [@valleyman86](https://forums.swift.org/u/valleyman86)\
**Post date:** [March 25, 2018, 11:29pm UTC](https://forums.swift.org/t/elvis-operator/11368/1 "2018-03-25T23:29:55Z")

</div>

I am wondering what people think of the idea of an actual [elvis operator](https://en.wikipedia.org/wiki/Elvis_operator)?

Right now we have a null coalescing operator which is nice for optionals. This however does not work with non-optional Bools. The reason I think this would be handy is that you could set a value of a Bool using functions that return Bool but allowing a backup if the first fails while not having to worry about side-effects.

Example:

> let value = Func1() ? Func1() : Func2() // Potential side-effects and Func1 is called twice. (What if Func1 incremented a value somewhere).

This can be fixed with (of course)

> let func1Result = Func1()  
> let value = func1Result ? func1Result : Func2()

But this kinda defeats the purpose of a ternary operator IMO and the code below is a lot nicer.

> let value = Func1() ?: Func2()

Now I did see this thread. [Replace ternary \_ ? \_ : \_ operator with a binary \_ ? \_ operator](https://forums.swift.org/t/replace-ternary-operator-with-a-binary-operator/11063)

It seems they want to remove the ternary operator completely because it uses a "?" it seems and that there is a replacement using an operator overload. The conversation there also got to adding an operator that seems to return an optional if the value is false. I think that is a slightly different issue and I would love to keep the current null coalescing and the ternary operators as is.

---

<div class="post-metadata">

**Author:** ![jawbroken](https://avatars.discourse-cdn.com/v4/letter/j/cc9497/32.png) [@jawbroken](https://forums.swift.org/u/jawbroken)\
**Post date:** [March 25, 2018, 11:40pm UTC](https://forums.swift.org/t/elvis-operator/11368/2 "2018-03-25T23:40:07Z")

</div>

Does this come up a lot? It sounds equivalent to short-circuiting logical OR to me, so I'm having trouble understanding why it is worth creating a new operator.

---

<div class="post-metadata">

**Author:** ![anthonylatsis](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/anthonylatsis/32/39232_2.png) [@anthonylatsis](https://forums.swift.org/u/anthonylatsis)\
**Post date:** [March 26, 2018, 12:12am UTC](https://forums.swift.org/t/elvis-operator/11368/3 "2018-03-26T00:12:20Z")

</div>

Indeed, that's the `||` operator. Making `?:` work the same way will take you 3 lines of code.

---

<div class="post-metadata">

**Author:** ![hlovatt](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/hlovatt/32/3044_2.png) [@hlovatt](https://forums.swift.org/u/hlovatt)\
**Post date:** [March 26, 2018, 3:34am UTC](https://forums.swift.org/t/elvis-operator/11368/4 "2018-03-26T03:34:48Z")

</div>

In Swift `?:` is `??`.

---

<div class="post-metadata">

**Author:** ![Erica\_Sadun](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/erica_sadun/32/243_2.png) [@Erica\_Sadun](https://forums.swift.org/u/Erica_Sadun)\
**Post date:** [March 26, 2018, 4:12am UTC](https://forums.swift.org/t/elvis-operator/11368/5 "2018-03-26T04:12:59Z")

</div>

The Elvis operator has to be one of the following cases:

```swift
// In a typesafe language, ?: must construct the same type left and right T ?: T and not T ?: U
// The only way to have a test is Boolean:
Bool ? Bool : Bool

// which then is shortened to
Bool ?: Bool

```

If you use it like many people do in C-like languages, you can test against "0" instead of testing for a bool:

```swift
// How to construct it in Swift
intValue != 0 ? intValue : fallbackValue

// What an Elvis would look like
intValue ?: fallbackValue

```

This is, again, of very limited use.

Finally, you can test it against a false-like condition, for example, an optional:

```swift
value != nil ? value! : fallbackValue

// which is 
value ?: fallbackValue

// exactly the same as
value ?? fallbackValue

```

The only other situation I can see is extending `??` and `if let` to other constructs with bias case loads

```swift
SomeEnum.caseName(value) ?? fallbackValue

```

But I wouldn't go Elvis on these. I'd rather use @stephencelis 's `.isCaseName?.value` (however that ends up being spelled.)

---

<div class="post-metadata">

**Author:** ![GarthSnyder](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/garthsnyder/32/969_2.png) [@GarthSnyder](https://forums.swift.org/u/GarthSnyder)\
**Post date:** [March 26, 2018, 6:24am UTC](https://forums.swift.org/t/elvis-operator/11368/6 "2018-03-26T06:24:21Z")

</div>

> [@Erica\_Sadun](#):
>
> If you use it like many people do in C-like languages, you can test against “0” instead of testing for a bool:

Yes. More generally, many other languages have a concept of "truthiness" such that 0 or NULL or an empty string can all qualify as false values for Boolean purposes. But since Swift allows only real Booleans in Boolean contexts, the utility of an Elvis operator seems much reduced.

---

<div class="post-metadata">

**Author:** ![hlovatt](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/hlovatt/32/3044_2.png) [@hlovatt](https://forums.swift.org/u/hlovatt)\
**Post date:** [March 26, 2018, 7:44am UTC](https://forums.swift.org/t/elvis-operator/11368/7 "2018-03-26T07:44:36Z")

</div>

It is easy enough to add Collection and hence String Elvis, this might be worth adding to the standard library since it is a common pattern in other languages:

```swift
extension Collection {
    static func ??(lhs: Self, rhs: @autoclosure () throws -> Self) rethrows -> Self {
        guard lhs.count != 0 else {
            return try rhs()
        }
        return lhs
    }
}

let s = ""
print(s ?? "Default") // Default

```

You could write something similar for Integers, but I would be against added the int version because it is rarely used in GCC and because it is very un-Swift like since testing against zero instead of a Bool is weird in Swift.

---

<div class="post-metadata">

**Author:** ![DCMaxxx](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/dcmaxxx/32/2624_2.png) [@DCMaxxx](https://forums.swift.org/u/DCMaxxx)\
**Post date:** [March 26, 2018, 1:48pm UTC](https://forums.swift.org/t/elvis-operator/11368/8 "2018-03-26T13:48:13Z")

</div>

> You could write something similar for Integers, but I would be against added the int version because it is rarely used in GCC and because it is very un-Swift like since testing against zero instead of a Bool is weird in Swift.

I feel the same way about your extension to Collection here : if it's 'un-Swift like' to test an integer against zero instead of using a `Bool`, why would testing a `Collection`'s `count` against zero would be better ?

---

<div class="post-metadata">

**Author:** ![hlovatt](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/hlovatt/32/3044_2.png) [@hlovatt](https://forums.swift.org/u/hlovatt)\
**Post date:** [March 26, 2018, 8:25pm UTC](https://forums.swift.org/t/elvis-operator/11368/9 "2018-03-26T20:25:18Z")

</div>

Reasons:

1. If you view an Optional as a collection of up to 1 element it makes sense.

2. It is a common idium in other languages that use reference semantics to return nil for empty collections/strings and therefore code like this is common practice.

3. It is useful to signal an error with an empty collection and have an easy way to provide a default.

---

<div class="post-metadata">

**Author:** ![anthonylatsis](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/anthonylatsis/32/39232_2.png) [@anthonylatsis](https://forums.swift.org/u/anthonylatsis)\
**Post date:** [March 26, 2018, 9:05pm UTC](https://forums.swift.org/t/elvis-operator/11368/10 "2018-03-26T21:05:16Z")

</div>

`Optional` formally isn't a collection and I don't see a way in which it resembles one.

> [@hlovatt](#):
>
> It is a common idium in other languages that use reference semantics to return nil for empty collections/strings and therefore code like this is common practice.

Yes, but Swift, being a high-level language, doesn't use such semantics. An empty array in C is a `NULL` pointer. In Swift, an empty array is a full-fledged instance.

> [@hlovatt](#):
>
> It is useful to signal an error with an empty collection and have an easy way to provide a default.

The nil-coalescing operator is unique and used only for optionals, and in my opinion it should be left as is.

I don't see the perspectives of introducing a _new_ operator for that purpose - the core team isn't tolerant towards new operators of that sort, and neither am I. But you are free to try, of course.  
You can always use the 'true-boolean' `_?_:_ ` which is even more useful and isn't that bad of an alternative. It's just a bit longer.

> [@hlovatt](#):
>
> ```swift
> extension Collection {
> static func ??(lhs: Self, rhs: @autoclosure () throws -> Self) rethrows -> Self {
> guard lhs.count != 0 else {
> return try rhs()
> }
> return lhs
> }
> }
> 
> ```

Better use `isEmpty`, `count` can lead to writing inefficient code when using the operator.  
Could be written in just a single line: ` return lhs.isEmpty ? try rhs() : lhs`

---

<div class="post-metadata">

**Author:** ![reitzig](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/reitzig/32/2054_2.png) [@reitzig](https://forums.swift.org/u/reitzig)\
**Post date:** [February 20, 2019, 12:51pm UTC](https://forums.swift.org/t/elvis-operator/11368/11 "2019-02-20T12:51:45Z")

</div>

What I sometimes miss is being able to write:

```swift
let a : A = maybeA() ?? throw SomeError()

```

But, unfortunately, `throw X` is not an expression (of type `Never`).

---

<div class="post-metadata">

**Author:** ![Nevin](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/nevin/32/617_2.png) [@Nevin](https://forums.swift.org/u/Nevin)\
**Post date:** [February 20, 2019, 4:59pm UTC](https://forums.swift.org/t/elvis-operator/11368/12 "2019-02-20T16:59:33Z")

</div>

> [@reitzig](#):
>
> What I sometimes miss is being able to write:
> 
> ```swift
> let a : A = maybeA() ?? throw SomeError()
> 
> ```
> 
> But, unfortunately, `throw X` is not an expression (of type `Never` ).

An extra pair of braces and parentheses (and a `try`) makes it work:

```swift
let a = try maybeA() ?? { throw SomeError() }()

```

---

<div class="post-metadata">

**Author:** ![Chris\_Lattner3](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/chris_lattner3/32/348_2.png) [@Chris\_Lattner3](https://forums.swift.org/u/Chris_Lattner3)\
**Post date:** [February 20, 2019, 5:26pm UTC](https://forums.swift.org/t/elvis-operator/11368/13 "2019-02-20T17:26:29Z")

</div>

Please start a new thread discussing the specific issue you raise here: I see no obvious reason we couldn't change 'throw' to be an expression returning `Never`.

That said, making that change wouldn't fix your code above, because ?? requires the left and right side to be the same base types, and Never is not an A.

---

<div class="post-metadata">

**Author:** ![Nevin](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/nevin/32/617_2.png) [@Nevin](https://forums.swift.org/u/Nevin)\
**Post date:** [February 20, 2019, 5:52pm UTC](https://forums.swift.org/t/elvis-operator/11368/14 "2019-02-20T17:52:30Z")

</div>

> [@Chris\_Lattner3](#):
>
> That said, making that change wouldn't fix your code above, because ?? requires the left and right side to be the same base types, and Never is not an A.

…but “`??`” uses an autoclosure for its right-hand side, and the code works if you manually wrap the expression in a closure, so I’m not sure why it doesn’t work as-is:

```swift
let x = Optional(0)

let y = x ?? fatalError()
// error: cannot convert value of type 'Never' to expected argument type 'Int'

let z = x ?? { fatalError() }()
// no error

```

---

<div class="post-metadata">

**Author:** ![reitzig](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/reitzig/32/2054_2.png) [@reitzig](https://forums.swift.org/u/reitzig)\
**Post date:** [February 20, 2019, 8:42pm UTC](https://forums.swift.org/t/elvis-operator/11368/15 "2019-02-20T20:42:42Z")

</div>

> [@Chris\_Lattner3](#):
>
> Please start a new thread discussing the specific issue you raise here:

[Done](https://forums.swift.org/t/combining-with-throwing-when-theres-no-reasonable-default/20722).
