If an absence of value is a good response in case the condition fails, then you can turn the return type into an optional and implement the function as follows:
public func get(pos : Int) -> Int?
{
if pos >= length {
return .None
}
return _data.get(pos);
}
If you need to return more information about the error, for example as an instance of NSError
, then you can create an enum which can either contain a value (called Some
) or an error (called Error
):
public enum RetVal {
case Some(Int)
case Error(NSError)
}
and change the implementation of your function to something like:
public func get(pos : Int) -> RetVal
{
if pos >= length {
return RetVal.Error(NSError(domain: "MyApp", code: 55, userInfo: nil))
}
return RetVal.Some(_data.get(pos));
}
and use it as follows:
let returnValue = get(55)
switch returnValue {
case .Some(let value):
println(value)
case .Error(let error):
println(error)
}
This prevent you from forgetting to handle exceptions (like in C#) or polluting your code with catch
es for any exception that a function/method call can raise (like in java). I didn't like absence of exceptions too at beginning, but now I see that my code is cleaner by avoiding them.