Skip to content

Instantly share code, notes, and snippets.

@callionica
Created December 13, 2016 19:18
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 callionica/11cb880c1752b1098b012d67d693d9cc to your computer and use it in GitHub Desktop.
Save callionica/11cb880c1752b1098b012d67d693d9cc to your computer and use it in GitHub Desktop.
let result = fn<-?(a, b)
// Swift Ver. 3.0.1 (Release)
// Platform: Linux (x86_64)
// Noodling with syntax for call avoidance with optional arguments
// Just to get a sense of what it could look like
// Given a function "fn" that takes 2 non-optional arguments
// We can enable this syntax:
// let result = fn<-?(a, b)
// where a and b are optionals
// fn will only be called if a and b are non-nil
// and result is an optional that will be nil if either a or b are nil
// otherwise result will be the result returned by fn (optional)
infix operator <-?
func <-? <T, R>(_ fn: (T)->R, _ t : T?)->R? {
return t.flatMap { fn($0) }
}
func <-? <T, U, R>(_ fn: (T, U)->R, _ v : (T?, U?))->R? {
guard let t = v.0, let u = v.1 else {
return nil;
}
return fn(t, u)
}
/////////////////////
func fn(_ value : Int)->Int {
print("fn(t) called")
return value;
}
func fn(_ value : Int, _ v2 : Int)->Int {
print("fn(t, u) called")
return v2;
}
/////////////////////
var x : Int? = 23;
let r0 = fn<-?(x)
print(r0 as Any)
x = nil
let r1 = fn<-?(x)
print(r1 as Any)
let r2 = fn<-?(x, 23)
print(r2 as Any)
let r3 = fn<-?(23, x)
print(r3 as Any)
let r4 = fn<-?(23, 101)
print(r4 as Any)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment