[swift-users] Parameter Validation

David Hart david at wittywings.fr
Sun Dec 6 14:49:17 CST 2015


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

Assert

func greetUser(user: String, times: Int) {
	assert(user.count > 0)
	assert(times > 0)

	for _ in 0..<times {
		print(“Hello \(user)”)
	}
}

Pros
* Easy to use

Cons
* Disabled in release
* Not unit-testable

Error-Handling

Pros
* Unit-testable

Cons
* Quickly litters all calling code with try's

In the case Error-Handling is used, what kind of ErrorType would you suggest?

enum GreetUserError : ErrorType {
	case UserEmpty
	case TimesInvalid
}

func greetUser(user: String, times: Int) throws {
	guard user.count > 0 else {
		throw GreetUserError.UserEmpty
	}

	guard times > 0 else {
		throw GreetUserError.TimesInvalid
	}

	for _ in 0..<times {
		print(“Hello \(user)”)
	}
}

Or should more generic re-usable errors be used? But less descriptive errors except if messages are provided every times:

enum ParameterError : ErrorType {
	case Empty(String)
	case NotInRange(String)
}

func greetUser(user: String, times: Int) throws {
	guard user.count > 0 else {
		throw ParameterError.Empty(“user")
	}

	guard times > 0 else {
		throw ParameterError.NotInRange(“times")
	}

	for _ in 0..<times {
		print(“Hello \(user)”)
	}
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20151206/b6401ad8/attachment.html>


More information about the swift-users mailing list