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;
}
@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