Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Created March 13, 2017 01:27
Show Gist options
  • Star 37 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save JadenGeller/1f4acd5cd07d4642c246d87ca25bd3e0 to your computer and use it in GitHub Desktop.
Save JadenGeller/1f4acd5cd07d4642c246d87ca25bd3e0 to your computer and use it in GitHub Desktop.
Class Cluster
class Number /* class cluser */ {
class Int8: Number {
var value: Swift.Int8
init(_ value: Swift.Int8) { self.value = value }
}
class Int: Number {
var value: Swift.Int
init(_ value: Swift.Int) { self.value = value }
}
class Float: Number {
var value: Swift.Float
init(_ value: Swift.Float) { self.value = value }
}
}
private protocol _Number {} /* Hack to allow self assingment */
extension Number: _Number {}
extension _Number {
init(_ value: Int) {
if let smallValue = Int8(exactly: value) {
self = Number.Int8(smallValue) as! Self
} else {
self = Number.Int(value) as! Self
}
}
init(_ value: Float) {
self = Number.Float(value) as! Self
}
}
print(type(of: Number(2))) // -> Int8
print(type(of: Number(10000))) // -> Int
print(type(of: Number(7.5))) // -> Float
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment