[swift-evolution] Compile time constraints on properties
James Froggatt
conductator at ntlworld.com
Wed Feb 3 17:35:43 CST 2016
As a side note to the natural numbers discussion, the idea of constraining properties at compile time seems like it would allow compile-time safety for all existing types.
Based on the previous ‘Partially Constrained Protocols’ discussion, a natural extension would be:
protocol<Self == TypeName where Self.instance.property == [literal]>
This would require a new keyword, ‘instance’ is an obvious candidate, though isn't great, but would allow function parameters and return types to make compile-time requirements on the value being passed, and make promises about values being returned, eliminating the need for failure conditions hidden inside the function itself.
Thus allowing:
protocol<Self == Int where Self.instance >= 0>
I'm not sure how feasible this would be, as it's presumably asking a lot in terms of compile-time code checking, but it would certainly cover constraining to natural numbers and eliminate many runtime failure conditions.
Honestly, I'm not happy with verbosity of the ‘where’ syntax in general; any other suggestions for syntax are welcome.
Usage:
typealias NaturalInt = protocol<Self == Int where Self.instance >= 0>
struct SafeSize {
var width: NaturalInt
var height: NaturalInt
}
extension Array {
subscript(safer index: NaturalInt) -> _Element {
return self[index]
}
}
I also feel I've seen this issue raised here before, so I may be reviving an old discussion.
From James F
More information about the swift-evolution
mailing list