【问题标题】:Change variables in guard statement in Swift?在 Swift 中更改保护语句中的变量?
【发布时间】:2017-05-16 05:39:15
【问题描述】:

我有一个如下所示的保护语句,如果结果不正确,我需要更改一个变量

func setGif() {
    var animalName = (String(format: "%03d", self.animal.speciesId!))
    guard animal.isDefault! == true else {
        animalName = animalName + "-merg"
        return
    }
    let gif = UIImage(gifName: animalName)
    self.gifIBO.setGifImage(gif, manager: gifManager)
    gifIBO.contentMode = UIViewContentMode.center
}

这样做会显示真值的 gif,但不会显示假值。如果警卫出现错误,我需要它用新值搜索 gif 名称。我在这里做错了什么?

【问题讨论】:

    标签: ios swift image var


    【解决方案1】:

    这是对guard 的不当使用。 guard 退出当前作用域,你不想这样做;你想继续前进。所以只需使用好旧的if。 (另外,永远不要将 Bool 与 true 作为条件进行比较;Bool 条件。)

    if animal.isDefault! {
       // it's true, do one thing
    } else {
       // it's false, do a different thing
    }
    

    在你的情况下,你可能只需要if:

    var animalName = (String(format: "%03d", self.animal.speciesId!))
    if !(animal.isDefault!) {
        animalName += "-merg"
    }
    let gif = UIImage(gifName: animalName)
    

    【讨论】:

    • 我明白了。我想使用守卫,因为随着应用程序变得越来越大,它最终会变成一个 if else 语句,我一直在阅读该守卫最好避免 if else @matt
    • 嗯,它不是。而且您似乎还认为guard 与“如果不是”相同,这也是错误的。
    • 我明白了。谢谢!
    【解决方案2】:

    这里不需要使用守卫。如果 isDefault 为 nil,也可以使用 animal.isDefault == .some(true) 来减少崩溃的可能性:

    func setGif() {
    
        var animalName = (String(format: "%03d", self.animal.speciesId!))
        if animal.isDefault == .some(true) else {
            animalName = animalName + "-merg"
        }
    
        let gif = UIImage(gifName: animalName)
        self.gifIBO.setGifImage(gif, manager: gifManager)
        gifIBO.contentMode = .center
    
    }
    

    【讨论】:

      猜你喜欢
      • 2020-05-11
      • 1970-01-01
      • 2018-03-03
      • 1970-01-01
      • 2011-04-01
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多