Search code examples
swiftreturnguard

How to use Guard when the function expect return value


I am a fan of the guard statements using Swift.

One thing I haven't fully understand is how (or even if) to use it inside a function that expect return value.

Simple example:

func refreshAudioMix() -> AVPlayerItem? {
   guard let originalAsset = rootNC.lastAssetLoaded else {
         return nil
   }
   let asset = originalAsset.copy() as! AVAsset
   ..... return AVPlayerItem ....
}

The issue with this approach is that I need to check the returned value each time. I am trying to understand if am I approaching this correctly or maybe even guard not needed here at all.

Thank you!


Solution

  • I'd say the use of guard isn't wrong. When the objects you're manipulating have a probability of being nil, it seems fair that you return an optional value.

    There's one other way (at least, but I don't see others right now) to handle that: write that your function can throw an error and throw it when you find nil in an optional value in a guard statement. You can even create errors so it's easily readable. You can read more about it here

    sample :

    enum CustomError: Error {
        case errorOne
        case errorTwo
        case errorThree
    }
    
    func refreshAudioMix() throws -> AVPlayerItem {
       guard let originalAsset = rootNC.lastAssetLoaded else {
             throw CustomError.errorOne
       }
       let asset = originalAsset.copy() as! AVAsset
       ..... return AVPlayerItem ....
    }