[swift-evolution] [Pitch] Constrains for numeric types: Int<1...10> Double<0.0...1.0>

Adrian Zubarev adrian.zubarev at devandartist.com
Wed May 11 12:45:01 CDT 2016


Hello Swift community. I'd like to discuss with you if we need something like this in Swift 3 or any future Swift version.

As you may know there is no way to constrain a numeric type expect for some scope internal assertion or precodintions which may produce a runtime error if the input value is out of the defined bound.

func foo(value: Int) {
		
	assert(value > 0 && value <= 10)

	// passed
}

How would it be if Swift would allow us to constraint numeric typs with ranges/intervals?

func newFoo(value: Int<1...10>) {
		
	// no need for an assertion any more
}

We could go even further and add more then one range/interval:

func someFoo(value: Int<0...20, 40...60>) { /* do some work */ }

Not only integers should have this ability but also floating point types like Double and Float. 

Alternative form might look like this:

Double[1.0...10.0]
Float[0.0...1.0, 10.0...100.0]

One downside of half opened ranges/intervals is the left side of its set. How do we exclude the left element?

1...10 means 1..<11 equals [1, 11)

But how can we create something like (0.0, 1.0), do we need a strange looking binary operator 0.0>..<1.0?

What do you think? I'd love to hear any feedback to this.

-- 
Adrian Zubarev
Sent with Airmail
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160511/f34122f1/attachment.html>


More information about the swift-evolution mailing list