Created
October 17, 2014 03:20
-
-
Save joshdholtz/251b02730edd52330cee to your computer and use it in GitHub Desktop.
Swift Generic Factory
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
// | |
// ViewController.swift | |
// SwiftTest | |
// | |
// Created by Josh Holtz on 8/3/14. | |
// Copyright (c) 2014 Josh Holtz. All rights reserved. | |
// | |
import UIKit | |
class ViewController: UIViewController { | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
var a = Maker<A>().make(); | |
a?.talk() // Outputs "Aaaaaa" | |
var b = Maker<B>().make(); | |
b?.talk() // Outputs "Bbbbbb" | |
var c = Maker<C>().make(); | |
c?.talk() // Outputs "Cccccc" | |
var d = Maker<D>().make(); | |
d?.talk() // Outputs "Dddddd" | |
} | |
} | |
struct Maker<T:Base> { | |
func make() -> T? { | |
return self.dynamicType.bake() | |
} | |
private static func bake() -> T? { | |
return T.create() | |
} | |
} | |
protocol Base { | |
init(); | |
func talk() | |
class func create() -> Self; | |
} | |
class A: Base { | |
required init() {} | |
func talk() { | |
println("Aaaaaa") | |
} | |
class func create() -> Self { return self() } | |
} | |
class B: Base { | |
required init() {} | |
func talk() { | |
println("Bbbbbb") | |
} | |
class func create() -> Self { return self() } | |
} | |
class C: B { | |
required init() {} | |
override func talk() { | |
println("Cccccc") | |
} | |
override class func create() -> Self { return self() } | |
} | |
class D: B, Base { | |
required init() {} | |
override func talk() { | |
println("Dddddd") | |
} | |
override class func create() -> Self { return self() } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment