Search code examples
swiftswitch-statementresulttype

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


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.


Solution

  • 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