Stuart Breckenridge

Swift 2 Adds Another Try Keyword

In Xcode 7 beta 6, Apple has introduced a new try? keyword to the Swift language. try? will attempt to perform an operation and if it succeeds the result is wrapped in an optional, otherwise the result is nil. One of the critical differences—and which I consider to be a downside—is that errors are no longer surfaced. In practice, try? looks something like this:

enum DayError: ErrorType, CustomStringConvertible
{
    case NeedADateError
    
    var description: String {
        switch self {
        case .NeedADateError:
            return "Error: A date must be provided."
        }
    }
}

func isItTuesday(date:NSDate?) throws -> String
{
    if date != nil
    {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "EEEE"
        let day = dateFormatter.stringFromDate(date!)
        
        if day == "Tuesday"
        {
            return "It is."
        } else
        {
            return "It isn't."
        }
    } else
    {
        throw DayError.NeedADateError
    }
}

Pretty simple: a function which throws an error if a parameter isn’t provided.1

The new try?:

// Example 1: result is nil with no error surfaced.
if let today = try? isItTuesday(nil)
{
    print("Date has been set.") // Never called.
} else
{
    print("Uh oh. No error handling. Result is nil.")
}
// Example 2: result is an optional. 
if let actual = try? isItTuesday(NSDate())
{
    print(actual) // Returns "It is." (Optional)
}
// Example 3: do-try-catch with error handling. 
do {
    let x = try isItTuesday(nil)
} catch
{
    print(error) // Error: A date must be provided.
}

I don’t think I’ll use try? all that often. I like to know why something failed and deal with it correctly.

  1. Obviously you can work around this scenario by using a non-optional parameter. ↩︎


Supported by