swift - 在守卫中创建非可选的以测试守卫条件

标签 swift guard

<分区>

我目前有这样的功能......

// this is a property
var currentString: String = ""

func doSomething() {
    let newString: String = goGetANewString()

    guard newString != currentString else {
        return
    }

    currentString = newString
}

但我发现在 guard 之外创建 newString 有点奇怪。

如果我将它移到 guard 中,它会提示它需要是可选的。

有没有办法在 guard 语句中创建 newString 并检查条件?

理想情况下我想要这样的东西,但就像我说的那样,它不能这样工作。

func doSomething() {
    guard let newString: String = goGetANewString(), newString != currentString else {
        return
    }

    currentString = newString
}

最佳答案

“技巧”是将 guard casevalue-binding pattern 一起使用对于作业:

func doSomething() {
    guard case let newString = goGetANewString(), newString != currentString else {
        return
    }

    currentString = newString
}

关于swift - 在守卫中创建非可选的以测试守卫条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48543112/

相关文章:

ruby-on-rails - Rails 4.2.2-Windows 7/: bundle exec guard 的 git Bash 上未显示测试结果

json - 为什么守卫不保护我免受 nil

iOS UIDocumentInteractionController PDF共享问题

ios - 使用 2 个组件在 UIPickerView 中水平移动隐藏行

swift - 字符串下标错误

ruby-on-rails - Guard Rspec :cli option is deprecated, 更改为 :cmd 选项

java - 第二个 return 语句嵌套在 if 语句中

ios - #import "Project-Swift.h"出现了一些奇怪的问题

uitableview - popToRootViewControllerAnimated 没有更新 UITableView

ruby-on-rails - 为什么在dockerizing Rails 应用程序后Guard 没有检测到文件更改?