Last active
August 29, 2015 14:14
-
-
Save kazk/90a8dfb5a587961f7e4f to your computer and use it in GitHub Desktop.
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
// MARK: unwrapped | |
public func unwrapped<A, B>(a: A?, b: B?) -> (A, B)? { | |
switch (a, b) { | |
case let (.Some(a), .Some(b)): return (a, b) | |
default: return nil | |
} | |
} | |
public func unwrapped<A, B, C>(a: A?, b: B?, c: C?) -> (A, B, C)? { | |
switch (a, b, c) { | |
case let (.Some(a), .Some(b), .Some(c)): return (a, b, c) | |
default: return nil | |
} | |
} | |
public func unwrapped<A, B, C, D>(a: A?, b: B?, c: C?, d: D?) -> (A, B, C, D)? { | |
switch (a, b, c, d) { | |
case let (.Some(a), .Some(b), .Some(c), .Some(d)): return (a, b, c, d) | |
default: return nil | |
} | |
} | |
// MARK: withUnwrapped | |
public func withUnwrapped<A, R>(a: A?, body: (A)->R) -> R? { // a.map(f) | |
return a.map(body) | |
} | |
public func withUnwrapped<A, B, R>(a: A?, b: B?, body: (A, B)->R) -> R? { | |
return unwrapped(a, b).map(body) | |
} | |
public func withUnwrapped<A, B, C, R>(a: A?, b: B?, c: C?, body: (A, B, C)->R) -> R? { | |
return unwrapped(a, b, c).map(body) | |
} | |
public func withUnwrapped<A, B, C, D, R>(a: A?, b: B?, c: C?, d: D?, body: (A, B, C, D)->R) -> R? { | |
return unwrapped(a, b, c, d).map(body) | |
} | |
// MARK: withDeducedType(s) | |
// contextually-deduced | |
// TODO: Better name. Maybe withRefinedType(s). | |
public func withDeducedType<A, B, R>(a: Any?, body: (A)->R) -> R? { | |
return (a as? A).map(body) | |
} | |
public func withDeducedTypes<A, B, R> | |
(a: Any?, b: Any?, body: (A, B)->R) -> R? | |
{ | |
return unwrapped(a as? A, b as? B).map(body) | |
} | |
public func withDeducedTypes<A, B, C, R> | |
(a: Any?, b: Any?, c: Any?, body: (A, B, C)->R) -> R? | |
{ | |
return unwrapped(a as? A, b as? B, c as? C).map(body) | |
} | |
public func withDeducedTypes<A, B, C, D, R> | |
(a: Any?, b: Any?, c: Any?, d: Any?, body: (A, B, C, D)->R) -> R? | |
{ | |
return unwrapped(a as? A, b as? B, c as? C, d as? D).map(body) | |
} | |
// let (a, b): (Int?, Int?) = (1, 1) | |
// unwrapped(a, b).map { $0 + $1 } //=> {Some 2} | |
//var anyA: Any = "a" | |
//var anyB: Any = "b" | |
//if let a = anyA as? String { | |
// a //=> "a" | |
//} | |
// This won't compile. | |
//if let (a, b) = (anyA, anyB) as? (String, String) { | |
//} | |
//if let (a, b) = unwrapped(anyA as? String, anyB as? String) { | |
// a //=> "a" | |
// b //=> "b" | |
//} | |
// unwrapped(anyA as? String, anyB as? String).map { $0 + $1 } //=> {Some "ab"} | |
// withDeducedTypes(anyA, anyB) {(a: String, b: String) in a + b} //=> {Some "ab"} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment