Last active
August 17, 2018 03:59
-
-
Save lazyvar/78a31257973a25a43f291060d91b4f10 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
//: Playground - noun: a place where people can play | |
import UIKit | |
func ward<T: AnyObject, A, Return>(_ object: T?, _ keyPath: KeyPath<T, (A) -> Return>, else defaultValue: Return) -> ((A) -> Return) { | |
return { [weak object] a in | |
guard let object = object else { | |
return defaultValue | |
} | |
return object[keyPath: keyPath](a) | |
} | |
} | |
func ward<T: AnyObject, A>(_ object: T?, _ keyPath: KeyPath<T, (A) -> Void>) -> ((A) -> Void) { | |
return { [weak object] a in | |
guard let object = object else { | |
return | |
} | |
object[keyPath: keyPath](a) | |
} | |
} | |
func ward<T: AnyObject, A, B>(_ object: T?, _ keyPath: KeyPath<T, (A, B) -> Void>) -> ((A, B) -> Void) { | |
return { [weak object] a, b in | |
guard let object = object else { | |
return | |
} | |
object[keyPath: keyPath](a, b) | |
} | |
} | |
func ward<T: AnyObject>(_ object: T?, _ keyPath: KeyPath<T, () -> Void>) -> (() -> Void) { | |
return { [weak object] in | |
guard let object = object else { | |
return | |
} | |
object[keyPath: keyPath]() | |
} | |
} | |
class MyClass { | |
let anOutput: () -> Void = { | |
print("here") | |
} | |
let boolOutput: (Bool) -> Bool = { boolVal in | |
return !boolVal | |
} | |
let multiParam: (String, Int) -> Void = { string, int in | |
print(string) | |
print(int) | |
} | |
} | |
extension KeyPath where Root == MyClass, Value == (() -> Void) { | |
static var anOutPut: KeyPath<MyClass, () -> Void> { return \MyClass.anOutput } | |
} | |
extension KeyPath where Root == MyClass, Value == ((Bool) -> Bool) { | |
static var boolOutput: KeyPath<MyClass, (Bool) -> Bool> { return \MyClass.boolOutput } | |
} | |
extension KeyPath where Root == MyClass, Value == ((String, Int) -> Void) { | |
static var multiParam: KeyPath<MyClass, (String, Int) -> Void> { return \MyClass.multiParam } | |
} | |
var vc: MyClass? = MyClass() | |
var funk: () -> Void = ward(vc, .anOutPut) | |
vc = nil | |
funk() | |
vc = MyClass() | |
let boolFunk = ward(vc, .boolOutput, else: false) | |
print(boolFunk(true)) | |
let wowza = ward(vc, .multiParam) | |
wowza("Hey", 2) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment