Skip to content

Instantly share code, notes, and snippets.

@danielctull
Created November 1, 2016 08:57
Show Gist options
  • Save danielctull/88e16e0f5d5ac97aaf084e7f7f4b1af9 to your computer and use it in GitHub Desktop.
Save danielctull/88e16e0f5d5ac97aaf084e7f7f4b1af9 to your computer and use it in GitHub Desktop.
// Used to make sure the value is 0 or above
public struct Positive {
let value: Float
public init(_ value: Float) {
if value < 0 {
self.value = 0
} else {
self.value = value
}
}
}
extension Positive {
public init?(_ string: String) {
guard let float = Float(string) else {
return nil
}
self.init(float)
}
}
extension Float {
public init(_ positive: Positive) {
self.init(positive.value)
}
}
// Float taken to be Positive values
extension Positive: FloatLiteralConvertible {
public init(floatLiteral value: Float) {
self.init(value)
}
}
// Integer taken to be Positive values
extension Positive: IntegerLiteralConvertible {
public init(integerLiteral value: Int) {
self.init(Float(value))
}
}
extension Positive: CustomStringConvertible {
public var description: String {
return value.description
}
}
extension Positive: CustomDebugStringConvertible {
public var debugDescription: String {
return value.debugDescription
}
}
extension Positive: RawRepresentable {
public init?(rawValue: Float) {
self.init(rawValue)
}
public var rawValue: Float {
return value
}
}
extension Positive: Equatable {}
public func ==(lhs: Positive, rhs: Positive) -> Bool {
return lhs.value == rhs.value
}
public func / (lhs: Positive, rhs: Positive) -> Positive {
return Positive(lhs.value / rhs.value)
}
public func * (lhs: Positive, rhs: Positive) -> Positive {
return Positive(lhs.value * rhs.value)
}
public func - (lhs: Positive, rhs: Positive) -> Positive {
return Positive(lhs.value - rhs.value)
}
public func + (lhs: Positive, rhs: Positive) -> Positive {
return Positive(lhs.value + rhs.value)
}
public func /= (inout lhs: Positive, rhs: Positive) {
lhs = lhs / rhs
}
public func *= (inout lhs: Positive, rhs: Positive) {
lhs = lhs * rhs
}
public func -= (inout lhs: Positive, rhs: Positive) {
lhs = lhs - rhs
}
public func += (inout lhs: Positive, rhs: Positive) {
lhs = lhs + rhs
}
public func > (lhs: Positive, rhs: Positive) -> Bool {
return lhs.value > rhs.value
}
public func < (lhs: Positive, rhs: Positive) -> Bool {
return lhs.value < rhs.value
}
public func >= (lhs: Positive, rhs: Positive) -> Bool {
return lhs.value >= rhs.value
}
public func <= (lhs: Positive, rhs: Positive) -> Bool {
return lhs.value <= rhs.value
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment