Last active
January 22, 2019 07:03
-
-
Save chungbkhn/804154fd5334bfe23c4306ff4a7ecac1 to your computer and use it in GitHub Desktop.
Binding in 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
import UIKit | |
class Box<T> { | |
typealias Listener = (T) -> Void | |
private var listener: Listener? | |
private var dispatchThread: DispatchQueue = DispatchQueue.main | |
var value: T { | |
didSet { | |
dispatchThread.async { [weak self] in | |
guard let `self` = self else { return } | |
self.listener?(self.value) | |
} | |
} | |
} | |
init(_ v: T) { | |
value = v | |
} | |
init(value: T, dispatchThread: DispatchQueue) { | |
self.value = value | |
self.dispatchThread = dispatchThread | |
} | |
} | |
extension Box { | |
func bind(listener: Listener?) { | |
self.listener = listener | |
} | |
func bindAndFire(listener: Listener?) { | |
self.listener = listener | |
listener?(value) | |
} | |
} | |
extension Box where T == String { | |
func bind(to label: UITextField) { | |
weak var weakInstance = label | |
self.listener = { (value) in | |
weakInstance?.text = value | |
} | |
} | |
func bindAndFire(to label: UITextField) { | |
self.bind(to: label) | |
listener?(value) | |
} | |
func bind(to button: UIButton) { | |
weak var weakInstance = button | |
self.listener = { (value) in | |
weakInstance?.setTitle(value, for: .normal) | |
} | |
} | |
func bindAndFire(to button: UIButton) { | |
self.bind(to: button) | |
listener?(value) | |
} | |
func bind(to imageView: UIImageView) { | |
weak var weakInstance = imageView | |
self.listener = { (value) in | |
weakInstance?.image = UIImage(named: value) | |
} | |
} | |
func bindAndFire(to imageView: UIImageView) { | |
self.bind(to: imageView) | |
listener?(value) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment