Skip to content

Instantly share code, notes, and snippets.

@rlaguilar
Forked from JadenGeller/Cluster.swift
Created March 13, 2017 14:33
Show Gist options
  • Save rlaguilar/066a537b5c51b300aa88f06ad55f0f61 to your computer and use it in GitHub Desktop.
Save rlaguilar/066a537b5c51b300aa88f06ad55f0f61 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