Last active
May 22, 2017 17:03
-
-
Save AlexanderNey/606b786f028e0a636f15 to your computer and use it in GitHub Desktop.
Null Coalescing Operator for Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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; | |
} |
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
_Null Coalescing Operator_
The will work like this
You can also chain this operator
value will be "This has a value" or if x,y,z are all bill it will fall back to "default"