Created
March 7, 2016 14:49
-
-
Save eonist/d4304919a736a9916181 to your computer and use it in GitHub Desktop.
swift factory pattern
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
import Foundation | |
protocol ILayout{ | |
init(_ args:Double...) | |
} | |
class Fillet:ILayout{ | |
required init(_ args:Double...){ | |
Swift.print("Fillet: " + "\(args.count)") | |
} | |
} | |
class Margin:ILayout{ | |
required init(_ args:Double...){ | |
Swift.print("Margin: " + "\(args.count)") | |
} | |
} | |
func instance(value:Any, _ layoutClassType:ILayout.Type) -> ILayout{ | |
let params:Array<Double> = value is Array<Double> ? value as! Array<Double> : [Double(String(value))!]; | |
let classType:ILayout.Type = layoutClassType | |
var instance:ILayout;// = typeOfObject.init(2,2,2,2) | |
switch(params.count){ | |
case 1: instance = classType.init(params[0]); break; | |
case 2: instance = classType.init(params[0],params[1]); break; | |
case 3: instance = classType.init(params[0],params[1],params[2]); break; | |
case 4: instance = classType.init(params[0],params[1],params[2], params[3]); break; | |
default:fatalError("ARGUMENT COUNT MISMATCH"); | |
} | |
return instance; | |
} | |
let margin:Margin = instance(4,Margin.self) as! Margin | |
let fillet:Fillet = instance(4,Fillet.self) as! Fillet |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment