What to put in switch cases that have nothing to do?

657 Views Asked by At

I started using Result as a return type and I mostly like it but when I have nothing to return for success then I am at a loss about what to do in that case statement. Any hints?

All that I could think of was let _ = 0

func createAppDirectory(_ searchPath: FileManager.SearchPathDirectory) -> Result<Void,Error>
...

    switch createAppDirectory(searchPath) {
    case .success(_): let _ = 0
    case .failure(let error): return .failure(error)
    }

I am beginning to think that maybe Result isn't a good fit when the success type is Void.

BTW createAppDirectory just creates Library/Application Support/<Bundle ID>. There is no value to return if it succeeds.

4

There are 4 best solutions below

2
Duncan C On BEST ANSWER

Use a break statement:

switch createAppDirectory(searchPath) {
case .success: 
  break
case .failure(let error): return .failure(error)
}

EDIT:

As Mojtaba pointed out, if you're not going to use the associated value for a particular case of your enum you can simply skip it. I've edited my answer above to remove the (_) from the .success case

3
Mojtaba Hosseini On

Just ignore it:

case .success: break

Also if you want absolutely no overwork when it isn't failure case, gaurd it at the very beginning of the scope:

guard case .failure(let error) = createAppDirectory(searchPath) else { return <#Value#> }
0
Sandeep On

Return simple void result,

switch createAppDirectory(searchPath) {
case .success: return .success(())
case .failure(let error): return .failure(error)
}
0
vadian On

If only the error is significant Result is inappropriate.

A better pattern is to throw the error and return nothing

func createAppDirectory(_ searchPath: FileManager.SearchPathDirectory) throws

...

do {
    try createAppDirectory(searchPath)
} catch { print(error)}