Create a gist now

Instantly share code, notes, and snippets.

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