In Swift, there's no simple way to define a subtype of some existing type with sort of additional constraints.
You can define your own float type:
struct NormalizedFloat {
var value: Float{
get{return internalValue}
set{
internalValue = Float.minimum(Float.maximum(newValue, 0), 1)
}
}
private var internalValue : Float = 0
}
But you may need to define bunch of operators, methods or properties or something like those to use it similar to Float.
protocol FloatSubtype {
var floatValue: Float {get}
init(floatValue: Float)
}
extension NormalizedFloat: FloatSubtype {
var floatValue: Float {
return value
}
init(floatValue: Float) {
self.value = floatValue
}
}
extension FloatSubtype {
static func + (lhs: Float, rhs: Self) -> Self {
return Self(floatValue: lhs + rhs.floatValue)
}
static func + (lhs: Self, rhs: Float) -> Self {
return Self(floatValue: lhs.floatValue + rhs)
}
static func + (lhs: Self, rhs: Self) -> Self {
return Self(floatValue: lhs.floatValue + rhs.floatValue)
}
static func - (lhs: Float, rhs: Self) -> Self {
return Self(floatValue: lhs - rhs.floatValue)
}
static func - (lhs: Self, rhs: Float) -> Self {
return Self(floatValue: lhs.floatValue - rhs)
}
static func - (lhs: Self, rhs: Self) -> Self {
return Self(floatValue: lhs.floatValue - rhs.floatValue)
}
static func * (lhs: Float, rhs: Self) -> Self {
return Self(floatValue: lhs * rhs.floatValue)
}
static func * (lhs: Self, rhs: Float) -> Self {
return Self(floatValue: lhs.floatValue * rhs)
}
static func * (lhs: Self, rhs: Self) -> Self {
return Self(floatValue: lhs.floatValue * rhs.floatValue)
}
static func / (lhs: Float, rhs: Self) -> Self {
return Self(floatValue: lhs / rhs.floatValue)
}
static func / (lhs: Self, rhs: Float) -> Self {
return Self(floatValue: lhs.floatValue / rhs)
}
static func / (lhs: Self, rhs: Self) -> Self {
return Self(floatValue: lhs.floatValue / rhs.floatValue)
}
//You may need many other operations or methods...
}
extension NormalizedFloat: ExpressibleByFloatLiteral, ExpressibleByIntegerLiteral {
init(floatLiteral value: Float) {
self.init(floatValue: value)
}
init(integerLiteral value: Int) {
self.init(floatValue: Float(value))
}
}
extension NormalizedFloat: CustomStringConvertible, CustomDebugStringConvertible {
var description: String {
return self.value.description
}
var debugDescription: String {
return self.value.debugDescription
}
}
With these setup, you can write something like this:
var norm1: NormalizedFloat = 0.124
var norm2: NormalizedFloat = 0.248
print(norm1 + norm2) //->0.37199998
There may be some ways to create a subtype more easily in the furture Swift. You should better visit swift.org.