[swift-users] Parameter Validation

Brent Royal-Gordon brent at architechies.com
Mon Dec 7 01:25:56 CST 2015

> When writing library code, what method of parameter validation would be suggested?

It depends.

If the data may come from somewhere out of your control, like a user or the network, throws (or an optional or Bool return value) is an appropriate choice.

If the data will come from a source which should “never” be wrong, like data that has already been parsed or a calculation you perform, then precondition() (rather than assert(), which is removed in production builds) is a good way to run a sanity check.

Basically, if you anticipate that the value could ever be invalid, use throws or an optional/boolean return. If you don’t think the value should ever be invalid, use precondition().

Brent Royal-Gordon

More information about the swift-users mailing list