如何在 iOS Swift 3 中使用 guard 和 condition?

How to using guard and condition in iOS Swift 3?

我想获取函数的结果并将其设置在另一个变量中(letvar)然后用条件检查它像这样:

guard galleryArr:Array<UIImage> = fetchGalleryImages() , galleryArr.count  != 0 {

}else{

}  

请告诉我解决此问题的正确方法。

试试这个:

func doSomething() -> Int? {
    guard let galleryArr = fetchGalleryImages(), galleryArr.count != 0 else {
        // you must return from doSomething in here, be it by throwing
        // a fatalError(), return nil, or some other value to indicate
        // that the call has failed
        return nil
    }

    // proceed with the function
    return ...
}

Swift 3.0

你可以像下面这样使用 guard 和 where 条件:

但一定是fetchGalleryImages()returnoptional值。

guard let galleryArr = fetchGalleryImages(), galleryArr.count > 0 else { 
 //What ever condition you want to do on fail or simply return 
}