Last active
September 5, 2015 22:22
-
-
Save pronebird/0ad37f0e78307c0a4443 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
//: Playground - noun: a place where people can play | |
import Foundation | |
//: We have to define init() method for ObjectType() to work | |
protocol Creatable { | |
init() | |
} | |
class Base: Creatable { | |
required init() {} | |
} | |
//: Bunch of dummies | |
class A:Base {} | |
class B:Base {} | |
class C:Base {} | |
class D:Base {} | |
class E:Base {} | |
class F:Base {} | |
//: Base chain that holds some object | |
class BaseChain<ObjectType:Creatable> { | |
var object: ObjectType | |
init() { | |
object = ObjectType() | |
} | |
func printSelf() -> Self { | |
print("Object.class = \(object.dynamicType); Chain.dynamicType = \(self.dynamicType)") | |
return self | |
} | |
} | |
//: Chain LEVEL 1 class | |
class Chain<ObjectType:Creatable> : BaseChain<ObjectType> { | |
func chain<DynamicType: Creatable>(type: DynamicType.Type) -> Subchain<DynamicType, Chain<ObjectType>> { | |
return Subchain<DynamicType, Chain<ObjectType>>(parent: self) | |
} | |
} | |
//: Chain LEVEL 1+ | |
class Subchain<ObjectType:Creatable, ParentObjectType> : BaseChain<ObjectType> { | |
var parent: ParentObjectType | |
init(parent parent_: ParentObjectType) { | |
parent = parent_ | |
super.init() | |
} | |
func chain<DynamicType: Creatable>(type: DynamicType.Type) -> Subchain<DynamicType, Subchain<ObjectType, ParentObjectType>> { | |
return Subchain<DynamicType, Subchain<ObjectType, ParentObjectType>>(parent: self) | |
} | |
func end() -> ParentObjectType { | |
return parent | |
} | |
} | |
/*: | |
Do some chained calls. | |
.end() allows to get back to parent chain | |
*/ | |
Chain<A>() | |
.chain(B.self) | |
.chain(C.self) | |
.chain(D.self) | |
.chain(E.self) | |
.chain(F.self) | |
.printSelf() | |
.end() | |
.printSelf() | |
.end() | |
.printSelf() | |
.end() | |
.printSelf() | |
.end() | |
.printSelf() | |
.end() | |
.printSelf() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment