【问题标题】:Binary operator '==' cannot be applied to operands of type '()' and 'Bool'二元运算符“==”不能应用于“()”和“布尔”类型的操作数
【发布时间】:2016-03-31 06:01:01
【问题描述】:

当我将代码更新为最新的 Swift 语法时,下面的代码出现错误。

  • 二元运算符“==”不能应用于“()”和“Bool”类型的操作数
  • 调用可以抛出,但它没有标记'try'并且错误没有处理

请帮助我找到解决方案。

【问题讨论】:

  • 您应该发布实际代码而不是屏幕截图。 See here 了解详情。谢谢。
  • @Gaurav writeToFile 不返回布尔值。它抛出一个错误。你应该使用 do try catch 错误处理

标签: ios swift


【解决方案1】:

你必须写在do catch块中,因为它会抛出异常

do {
    try str.writeToFile("yourPath", atomically: true, encoding: NSUTF8StringEncoding)
}
catch {

}

您还可以按如下方式捕获错误:

do {
    try str.writeToFile("yourPath", atomically: true, encoding: NSUTF8StringEncoding)
}
catch let error as NSError {
    print(error.description)
}

你也可以通过guard和defer:http://nshipster.com/guard-and-defer/swift中的新概念

【讨论】:

    【解决方案2】:

    writeToFile 方法抛出异常。使用这个块

      do {
          try str.writeToFile(filename, atomically: true, encoding: NSUTF8StringEncoding)
         }
    catch {
    // failed to write file – bad permissions, bad filename, missing permissions, or more likely it can't be converted to the encoding
          }
    

    【讨论】:

      【解决方案3】:

      为了解决您的问题,请尝试使用try catch 构造。

           do {
             try text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding)
           }
           catch
           {
      
           }
      

      【讨论】:

        【解决方案4】:

        函数 writeToFilePath(path, atomically:, encoding:) 不返回任何内容(它的返回类型是 Void 或 ())并且您试图将任何内容与布尔值进行比较。

        第二个错误行解释了这个例程如果失败会抛出一个错误。您需要使用 Swift 的错误处理机制来处理错误,而不是尝试将函数结果与布尔值进行比较。

        【讨论】:

          【解决方案5】:

          在 Swift 中,它不再返回 Bool。这是文档中的描述:

          func writeToFile(_ path: String,
                atomically useAuxiliaryFile: Bool,
                  encoding enc: UInt) throws
          

          因为它会抛出错误,你应该尝试忽略这样的错误:

          try! contentsOfFile.writeToFile("yourPath", atomically: true, encoding: NSUTF8StringEncoding)
          

          或者你捕获并处理错误:

          do {
              try contentsOfFile.writeToFile("yourPath", atomically: true, encoding: NSUTF8StringEncoding)
          } catch let error {
              // handle error here
          }
          

          【讨论】:

            【解决方案6】:

            以上答案都是正确的!!!这些调用可能会引发异常。

            do {
                contentsOfFile str.writeToFile(path, atomically: true, encoding:    NSUTF8StringEncoding)
            }
            catch {
            
            }
            

            【讨论】:

              猜你喜欢
              • 2018-07-23
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2015-08-29
              相关资源
              最近更新 更多