Skip to content

Instantly share code, notes, and snippets.

@AlexanderNey
Last active May 22, 2017 17:03
Show Gist options
  • Save AlexanderNey/606b786f028e0a636f15 to your computer and use it in GitHub Desktop.
Save AlexanderNey/606b786f028e0a636f15 to your computer and use it in GitHub Desktop.
Null Coalescing Operator for Swift
//
// OptionalOperators.swift
//
// Created by Alexander Ney on 22/06/2014.
// Copyright (c) 2014 Alexander Ney. All rights reserved.
//
// Null Coalescing Operator
operator infix | {associativity right}
func | (optional: Any?, defaultValue: Any) -> Any
{
return optional ? optional! : defaultValue;
}
@AlexanderNey
Copy link
Author

_Null Coalescing Operator_

The will work like this

var optionalOrDefaut = optional | default

You can also chain this operator

var x : String? = nil
var y : String? = nil
var z : String? = "This has a value"

var value = x | y | z | "default"

value will be "This has a value" or if x,y,z are all bill it will fall back to "default"

@sdiprizio
Copy link

Although your implementation works great in Playground, in a real project (Xcode-DP2) the compiler wants to unwrap the optional... (bug ?)

What about this implementation :

operator infix | {associativity right}
func | <T> (optional: T?, defaultValue: T) -> T {
    return optional ? optional! : defaultValue;
}

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