【问题标题】:Condition after variable binding in guard swift compilation issue后卫快速编译问题中变量绑定后的条件
【发布时间】:2016-10-01 16:40:53
【问题描述】:

我正在使用来自 Swift 3.0(在 Xcode 8.0 中)的 nice guard 语句,并具有以下功能:

func parse(suffix s: String) throws -> Instruction {
    guard let count = Int(s) where count >= 0 else {
      throw InstructionParsingError(message: s + " should be a positive integer")
    }
    return CallInstruction(argCount: count)
}

我的问题是 swift 编译器两次抱怨包含我的保护语句的行:

CallInstruction.swift:42:29: Boolean condition requires 'where' to separate it from variable binding
CallInstruction.swift:42:30: Expected ',' joining parts of a multi-clause condition

我试过了

  • , 替换where 然后第二个错误消失但第一个错误仍然存​​在。
  • where 替换为, where 但随后甚至无法解析此行
  • 将其中的count 替换为Int(s),但出现相同的错误。

我应该如何更改我的代码才能编译? (我的意思是,我的意思是,我当然可以有多个守卫,或者 ifs 或 switch,但是从我读到的关于守卫语句的内容,我应该能够有一个清晰可读的行)。

【问题讨论】:

  • guard let count = Int(s), count >= 0 else 应该使用 Swift 3/Xcode 8 编译。也许源代码中有一些不可见的空格或控制字符?
  • 哦,好的,更换后我在 xcode 中清理了我的产品,所有错误都消失了。谢谢!

标签: swift swift-guard


【解决方案1】:

为了解决这个问题,我建议您在保护语句中使用模型 Swift 语法,将 where 替换为 ,

func  parse(suffix s: String) {
    guard let count = Int(s), count >= 0 else {
         return
    }
}

也可以使用if let 声明:

func  parseTwo(suffix s: String) {
    if let count = Int(s), count >= 0  {
        // done
        print(count)
    } else {
        return
    }
}

【讨论】:

    猜你喜欢
    • 2011-02-20
    • 2019-05-14
    • 2023-03-13
    • 2012-10-28
    • 2017-12-29
    • 2014-01-22
    • 1970-01-01
    • 2021-03-29
    • 1970-01-01
    相关资源
    最近更新 更多