【问题标题】:How to using guard and condition in iOS Swift 3?如何在 iOS Swift 3 中使用保护和条件?
【发布时间】:2017-12-20 07:00:44
【问题描述】:

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

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

}else{

}  

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

【问题讨论】:

  • fetchGalleryImages() 是如何定义的?它返回一个数组还是一个可选数组?

标签: ios swift swift3 conditional-statements guard


【解决方案1】:

Swift 3.0

你可以像下面这样用户守卫和 where 条件:

但一定是fetchGalleryImages()返回optional值。

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

【讨论】:

    【解决方案2】:

    试试这个:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-21
      • 1970-01-01
      • 1970-01-01
      • 2019-07-11
      • 2016-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多