Skip to content

Instantly share code, notes, and snippets.

@bjhomer
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjhomer/b0345c44dfbdb8cb7398 to your computer and use it in GitHub Desktop.
Save bjhomer/b0345c44dfbdb8cb7398 to your computer and use it in GitHub Desktop.
Nil-fallback operator suggestions
// Looking for a Swift replacement for the following ObjC code:
// id x = foo ?: bar
//
// Which of the following do you like, if any? Any other suggestions?
// (Note that '?' cannot be used in a custom operator.)
x = foo !|| bar
x = foo |< bar
x = foo ||< bar
x = foo <|| bar
x = foo <| bar
x = foo <= bar
x = foo <- bar
x = foo ||| bar
@rosskimes
Copy link

Unfortunately, it does not look like you can use a ? in an overloaded operator.

@bjhomer
Copy link
Author

bjhomer commented Jul 25, 2014

[sigh] True. Updated.

@rbrockerhoff
Copy link

x = foo ||: bar

@lilyball
Copy link

You can't use : in an operator either. Otherwise I'd say !:.

@rosskimes
Copy link

I really think there should be an ! in the operator. It helps to hint that there is (or at least could be) an optional unwrapping occurring. Maybe something like !=.

@bjhomer
Copy link
Author

bjhomer commented Jul 25, 2014

I'm not sure the operator should be doing an unwrap; it should leave the type of the lhs exactly as it was. After all, since the RHS may be an optional as well, there is no guarantee that the return value of this operator is a non-Optional type.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment