[swift-evolution] [Idea] Add forced conversion for Error catching pattern matching

Thorsten Seitz tseitz42 at icloud.com
Tue Mar 22 02:14:54 CDT 2016


> Am 22.03.2016 um 07:19 schrieb Tyler Fleming Cloutier via swift-evolution <swift-evolution at swift.org>:
> 
> These I think add noise in terms of someone reading the code. Now not only do they need to know Swift’s error handling mechanism, but also they have to be familiar with my custom wrapper around it.

That is the case with all abstractions so I don't see why that should be a problem here, especially as the last example given by Brent was very succinct and expressive. 

-Thorsten 


>>> On Mar 21, 2016, at 8:26 PM, Brent Royal-Gordon <brent at architechies.com> wrote:
>>> 
>>> do {
>>>   let action = chooseAction(game)
>>>   game = try game.applyAction(action)
>>> } catch let e as ActionError {
>>>   game.failedAction = e
>>> } catch _ {
>>>   fatalError(“This is an unfortunate bit of noise :/")
>>> }
>> 
>> If you're just worried about the noise...
>> 
>>    try! {
>>        do {
>>            let action = chooseAction(game)
>>            game = try game.applyAction(action)
>>        }
>>        catch let e as ActionError {
>>            game.failedAction = e
>>        }
>>    }()
>> 
>> Or if that's too much syntax:
>> 
>>    func mustSucceed<Return>(function: () throws -> Return) -> Return {
>>        return try! function()
>>    }
>>    
>>    mustSucceed {
>>        do {
>>            let action = chooseAction(game)
>>            game = try game.applyAction(action)
>>        }
>>        catch let e as ActionError {
>>            game.failedAction = e
>>        }
>>    }
>> 
>> Or, if you use this specific ActionError logic widely, you can put that in a function:
>> 
>>    func catchActionError<Return>(function: () throws -> Return) -> Return? {
>>        do {
>>            return try function()
>>        }
>>        catch e as ActionError {
>>            game.failedAction = e
>>            return nil
>>        }
>>        catch {
>>            fatalError()
>>        }
>>    }
>>    
>>    catchActionError {
>>        let action = chooseAction(game)
>>        game = try game.applyAction(action)
>>    }
>> 
>> -- 
>> Brent Royal-Gordon
>> Architechies
> 
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution


More information about the swift-evolution mailing list