Created
January 8, 2016 21:58
-
-
Save irace/65dfe10577112787a63a to your computer and use it in GitHub Desktop.
Trying to model a sequence of view controllers.
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
struct ViewControllerSequence { | |
typealias ViewControllerProducer = Void -> UIViewController | |
private var storage = TypeDictionary<ViewControllerProducer>() | |
private var producers: [ViewControllerProducer] | |
init(_ producers: [ViewControllerProducer]) { | |
self.producers = producers | |
} | |
mutating func next(previous: UIViewController? = nil) -> UIViewController? { | |
if let previous = previous, producer = storage.get(previous.dynamicType) { | |
return producer() | |
} | |
else { | |
return produceAndCacheNextViewController() | |
} | |
} | |
mutating func produceAndCacheNextViewController() -> UIViewController? { | |
guard !producers.isEmpty else { return nil } | |
let producer = producers.removeFirst() | |
let controller = producer() | |
if let nextProducer = producers.first { | |
storage.set(controller.dynamicType, value: nextProducer) | |
} | |
return controller | |
} | |
} | |
struct TypeDictionary<T> { | |
private var storage = [Int: T]() | |
mutating func set(type: AnyClass, value: T) { | |
storage[hashFromType(type)] = value | |
} | |
func get(type: AnyClass) -> T? { | |
return storage[hashFromType(type)] | |
} | |
private func hashFromType(type: AnyClass) -> Int { | |
return "\(type)".hashValue | |
} | |
} | |
private lazy var viewControllerSequence: ViewControllerSequence = ViewControllerSequence([ | |
{ [unowned self] in PhoneNumberFormViewController(delegate: self) }, | |
{ [unowned self] in VerifyNumberFormViewController(delegate: self) }, | |
{ [unowned self] in SignUpFormViewController(delegate: self) } | |
]) | |
private func showNextViewController(previousViewController: UIViewController) { | |
if let nextViewController = viewControllerSequence.next(previousViewController) { | |
previousViewController.showViewController(nextViewController, sender: nil) | |
} | |
else { | |
// The flow is complete! | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment