Thursday, July 23, 2015

init? vs. init throws

David Owens II:

What I’ve come to realize is, my problem is really about the callsite, I actually always want to use throws. The simple fact is that I can return more information about the failure and let the caller decide if they care about it or not.

But if the caller doesn’t care about it, this makes the callsite ugly.

Ok, so let’s make it better:

func trythrow<T>(@autoclosure fn: () throws -> T?) -> T? {
    do { return try fn() }
    catch { return nil }
}

func example3() {
    guard let tt = trythrow(try Foo(throwable: 0)) else {
        print("error")
        return
    }
    
    print("Foo(throwable:) creation passed")
    
}

This gets us into a happy place again. We can turn failures where we do not care about the specific reasons into a code path that is more natural. If this becomes a pattern, it begs the question why this wouldn’t be just built into the language.

This thread suggests doing that by adding try?, which looks like a good idea.

1 Comment RSS · Twitter


[…] is a good addition that was suggested last month. I’m not worried about errors being ignored because the compiler warns if the […]

Leave a Comment