Created
September 15, 2015 23:43
-
-
Save phin/278c0d1869ba24402e6a to your computer and use it in GitHub Desktop.
Swift - Coffescript "?" equivalent
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
import Cocoa | |
/* | |
CoffeeScript funfact: I have 2 values `a` and `b`, and wanted a 3rd value `x` that is equal to `a` if it exists, otherwise is `b` if it exists, or is `undefined` if both are | |
sami [18:27] | |
I was able to do that with just `x = a ? b` | |
*/ | |
infix operator ?| {} | |
func ?| <T>(left: T?, right: T?) -> T? { | |
if (left != nil) { | |
return left | |
} | |
return right // Either returns right or nil | |
} | |
class Car:NSObject { | |
internal override var description:String { return "Car"} | |
} | |
class Bike:NSObject { | |
internal override var description:String { return "Bike"} | |
} | |
class Skateboard:NSObject { | |
internal override var description:String { return "Skateboard"} | |
} | |
let carThatIMayOwn:Car? = nil | |
let bikethatIMayOwn:Bike? = Bike() // Oh, I have a bike instance! | |
let skateboardIMayOwn:Skateboard? = Skateboard() // Also have a skateboard | |
println("Today I will take my \(carThatIMayOwn ?| bikethatIMayOwn ?| skateboardIMayOwn)") | |
// Prints "Today I will take my Optional(Bike)" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This produced the same result, but maybe I'm missing something?