Skip to content

Instantly share code, notes, and snippets.

@wookiee
Created July 18, 2020 22:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wookiee/70547c03a0df58b349eed8d600fced9b to your computer and use it in GitHub Desktop.
Save wookiee/70547c03a0df58b349eed8d600fced9b to your computer and use it in GitHub Desktop.
import Foundation
@propertyWrapper public struct Percentage<Value: FloatingPoint> {
private var storage: Value
private let upperBound: Value
public init(wrappedValue: Value, upperBound: Value = (1.0 as! Value)) {
self.storage = wrappedValue
self.upperBound = upperBound
}
public var wrappedValue: Value {
get {
switch storage {
case ...0:
return 0
case 1...:
return 1
default:
return storage
}
}
set {
assert((0...upperBound).contains(newValue),
"Percentage (\(newValue)) > \(upperBound), which is illegal.")
storage = newValue
}
}
public var projectedValue: Value {
get {
return storage
}
set {
storage = newValue
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment