Skip to content

Instantly share code, notes, and snippets.

@ahcode0919
Last active April 17, 2017 22:56
Show Gist options
  • Save ahcode0919/569d82560de71213999f93f0dc9ef7bc to your computer and use it in GitHub Desktop.
Save ahcode0919/569d82560de71213999f93f0dc9ef7bc to your computer and use it in GitHub Desktop.
Example of the factory pattern in Swift
//Factory Pattern (Creational)
//Allows logic of which type will be created to be handled by a method
protocol SimpleType {
var simpleName: String { get }
}
struct Type1: SimpleType {
var simpleName: String = "Type1"
}
struct Type2: SimpleType {
var simpleName: String = "Type2"
}
/*
Factory Method
Handles logic of which specific struct to return
*/
func simpleTypeFactory(getType type: Int) -> SimpleType? {
switch type {
case 1:
return Type1()
case 2:
return Type2()
default:
return nil
}
}
let type1 = simpleTypeFactory(getType: 1)
type1?.dynamicType //Type1
type1?.simpleName //"Type1"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment