Last active
March 6, 2017 18:28
-
-
Save DigitalLeaves/1b7536b921cda7d7066b328d30a2eeb7 to your computer and use it in GitHub Desktop.
A Generic number that allows us to perform generic operations on Int/Double/Float, etc, and a sequence extensions like "add 1"
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 protocol GenericNumber : Comparable, ExpressibleByFloatLiteral, ExpressibleByIntegerLiteral, SignedNumber { | |
var value :Double { set get } | |
init(_ value: Double) | |
} | |
public func +<T: GenericNumber> (lhs: T, rhs: T) -> T { return T(lhs.value + rhs.value) } | |
public func -<T: GenericNumber> (lhs: T, rhs: T) -> T { return T(lhs.value - rhs.value) } | |
public func +<T: GenericNumber> (lhs: T, rhs: Double) -> T { return T(round(lhs.value + rhs)) } | |
public func -<T: GenericNumber> (lhs: T, rhs: Double) -> T { return T(lhs.value - rhs) } | |
extension GenericNumber { | |
mutating func addDouble(_ num: Double) -> Void { | |
self = Self.init(self.value + num) | |
} | |
mutating func substractDouble(_ num: Double) -> Void { | |
self = Self.init(self.value - num) | |
} | |
} | |
extension Int: GenericNumber { | |
public var value: Double { | |
get { | |
return Double(self) | |
} | |
set { | |
self = Int(round(value)) | |
} | |
} | |
public init(floatLiteral value: FloatLiteralType) { | |
print("\(value) -> \(Int(round(value)))") | |
self = Int(round(value)) | |
} | |
} | |
extension Float: GenericNumber { | |
public var value: Double { | |
get { | |
return Double(self) | |
} | |
set { | |
self = Float(value) | |
} | |
} | |
} | |
extension Double: GenericNumber { | |
public var value: Double { | |
get { | |
return self | |
} | |
set { | |
self = value | |
} | |
} | |
} | |
extension Sequence where Iterator.Element: GenericNumber { | |
func addNumber(_ num: Double) -> [Iterator.Element] { | |
return self.map({ print("\($0) + \(num) = \($0 + num)"); return $0 + Double(num) }) | |
} | |
} | |
let a = 1 | |
let b = a + 5.732 | |
print("a = \(a)") | |
print("b = \(b)") | |
let numberToAdd = 5.732 | |
let arrayOfNumbers = [1, 2.227382, 3, 4.93246] | |
print("\(arrayOfNumbers) --(\(numberToAdd))--> \(arrayOfNumbers.addNumber(numberToAdd))") | |
// Prints:5.732 -> 6 | |
// a = 1 | |
// b = 7 | |
// 1 + 5.732 = 7 | |
// 2 + 5.732 = 8 | |
// 3 + 5.732 = 9 | |
// 4 + 5.732 = 10 | |
// [1.0, 2.227382, 3.0, 4.9324599999999998] --(5.732)--> [7.0, 8.0, 9.0, 11.0] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment