当函数期望 return 值时如何使用 Guard

How to use Guard when the function expect return value

我喜欢使用 Swift 的 guard 语句。

我还没有完全理解的一件事是如何(或者即使)在期望 return 值的 function 中使用它。

简单示例:

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

这种方法的问题是我每次都需要检查 returned 值。我试图了解我是否正确地处理了这个问题,或者甚至 guard 这里根本不需要。

谢谢!

我会说 guard 的使用没有错。当你操纵的对象有可能为零时,你 return 一个可选值似乎很公平。

还有另一种方法(至少,但我现在看不到其他方法)来处理这个问题:写下你的函数可以抛出一个错误,当你在 guard 语句的可选值中找到 nil 时抛出它.您甚至可以创建错误以使其易于阅读。你可以 read more about it here

样本:

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 ....
}