Last active
November 14, 2023 15:45
-
-
Save rintaro/9eadc2720ac8be6a7898 to your computer and use it in GitHub Desktop.
Swift Class Cluster demo
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
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 | |
} | |
} |
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
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