Basic Operators : Quick Reference Guide

I made a Quick Reference Guide (One Pager) for Basic Operators.

What thinks?

:rainbow::pray::rainbow:

4 Likes

I don't think the comment on ?? is correct? I think a ?? b is more equivalent to this:

{
  if let a { 
    return a 
  } else {
    return b
  }
}()

Note that the if-let construct uses optional binding, and performs a nil-check and unwrap in one operation. Thus, it does not run the risk of a becoming nil between the check and the unwrap. I think ?? behaves similarly.

One could probably verify this by expressing a as a computed property which returns a non-nil on first access, and nil on the second.

1 Like

Where are the bitwise and shift operators?

1 Like

@sveinhal, thank you for the comment. The quick reference guide above is essentially a summary of this page:

https://docs.swift.org/swift-book/LanguageGuide/BasicOperators.html

...

How would you do this, programmatically, please?

Thanks, again.

:rainbow::pray::rainbow:

1 Like

Thank you for the comment, @jeremyp .

This quick reference guide is a summary of this page :

https://docs.swift.org/swift-book/LanguageGuide/BasicOperators.html

Bitwise operators are on this page :

https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html

Which I might make a quick reference guide for in a future release if I have the energy for it.

:rainbow::pray::rainbow:

1 Like
var suddenlyNil: Int? {
    Bool.random() ? nil : 1
}

let fallback = 2

let a = suddenlyNil ?? fallback
let b = suddenlyNil != nil ? suddenlyNil! : fallback

a never crashes, but b sometimes :bomb: with the following trap:

__lldb_expr_40/20230202_085714.playground:15: Fatal error: Unexpectedly found nil while unwrapping an Optional value

This is because in the first case, suddenlyNil is read twice: First to compare agains nil (which it may or may not be, randomly), and then again when force unwrapping! In approx 25% of cases, the value is non-nil on the first access, but nil on the second, causing a crash.

In the second case, it never crashes, because the value is nil-checked and unwrapped in a single operation.

I think the statement that value ?? fallback and value != nil ? value! : fallback are identical is strictly false. However, it is kinda conceptually true, so I guess it gives a pretty good intuition about what is going on.

So it isn't too bad as long as it doesn't give off the impression that the two are equally safe.

3 Likes

Yes except a need not be a variable, not even a manufactured computed one. You are also allowed to do

let a = functionWithSideEffects() ?? fallback

So it's very important that the left side of ?? is only dereferenced once in any illustrative piece of code.

2 Likes