Skip to content

Instantly share code, notes, and snippets.

@joanmolinas
Last active February 1, 2016 17:18
Show Gist options
  • Save joanmolinas/e146753935eae92d23e5 to your computer and use it in GitHub Desktop.
Save joanmolinas/e146753935eae92d23e5 to your computer and use it in GitHub Desktop.
Factory Pattern
//Enum
enum Country {
case Spain, France
}
//Classes
class Spain : Language {
func code() -> String {
return "SP"
}
func name() -> String {
return "Spain"
}
}
class France : Language {
func code() -> String {
return "FR"
}
func name() -> String {
return "France"
}
}
class LanguageFactory {
class func languageWithCountry(country : Country) -> Language? {
switch country {
case .Spain:
return Spain()
case .France:
return France()
default:
return nil
}
}
}
//Protocol
protocol Language {
func code() -> String
func name() -> String
}
let noCountry = "no country available"
LanguageFactory.languageWithCountry(.Spain)?.code() ?? noCountry
LanguageFactory.languageWithCountry(.France)?.code() ?? noCountry
LanguageFactory.languageWithCountry(.US)?.code() ?? noCountry
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment