[swift-users] Parameter Validation

David Hart david at wittywings.fr
Mon Dec 7 01:49:32 CST 2015


I’m looking at the special case of library code. If I surface an API in a library, it’s the library user who will call this function. Would you regard this as an assert or throws scenario?

> On 07 Dec 2015, at 08:25, Brent Royal-Gordon via swift-users <swift-users at swift.org> wrote:
> 
>> 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
> Architechies
> 
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users



More information about the swift-users mailing list