Skip to content

Instantly share code, notes, and snippets.

@rintaro
Last active November 14, 2023 15:45
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rintaro/9eadc2720ac8be6a7898 to your computer and use it in GitHub Desktop.
Save rintaro/9eadc2720ac8be6a7898 to your computer and use it in GitHub Desktop.
Swift Class Cluster demo
public class Pokemon {
private init() {}
public var name: String { fatalError() }
}
private class Pikachu: Pokemon {
override var name: String { return "ピカチュウ" }
}
private class Snorlax: Pokemon {
override var name: String { return "カビゴン" }
}
extension Pokemon: _Cluster {
public convenience init?(_ arg: String) {
self.init {
switch arg {
case "pika": return Pikachu()
case "snor": return Snorlax()
default: return nil
}
}
}
}
private protocol _Cluster {}
extension _Cluster {
init?(@noescape _cluster: () -> Self?) {
guard let _self = _cluster() else { return nil }
self = _self
}
}
Pokemon("pika")?.name // -> "ピカチュウ"
Pokemon("snor")?.name // -> "カビゴン"
Pokemon("bang")?.name // -> nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment