【问题标题】:Swift ternary syntax errorSwift 三元语法错误
【发布时间】:2015-05-09 06:36:29
【问题描述】:

我以前一直使用 Objective-C 进行编程,而且我是 Swift 的新手。这个错误 Xcode 让我很困惑。

func renderBufferAreaBAUp(yOffset: CGFloat, amount: CGFloat, ifLeft: Bool)
{     
        var topViewIndexForIndexAdjust = ifLeft?leftTopIndex:rightTopIndex
}

在这一行我打算使用三元。 leftTopIndex 和 rightTopIndex 都是 Int 类型。然而,Xcode 给了我这一行的那些,

一行中的连续语句必须用';'分隔 预期表达

谁能告诉我这些是什么意思?谢谢。

【问题讨论】:

    标签: swift ternary-operator


    【解决方案1】:

    Swift 错误消息通常含糊不清且没有帮助。您真正的问题是 Swift 需要在 ?: 周围留出一些空间。

    var topViewIndexForIndexAdjust = ifLeft ? leftTopIndex : rightTopIndex
    

    【讨论】:

      【解决方案2】:

      您必须使用空格来分隔操作数和运算符:

      var topViewIndexForIndexAdjust = ifLeft ? leftTopIndex : rightTopIndex
                                             ^ ^            ^ ^
      

      Swift 对此非常严格——即使是这行明显正确的代码:

      let val =12
      

      产生编译错误。

      【讨论】:

        【解决方案3】:

        为三元运算符的神秘 Swift 错误消息而苦苦挣扎

        错误 1

        incrementValue = incrementValue == 0?1:incrementValue //errors saying add ";", consecutive statements must be separated by ";"
        

        错误 2

        incrementValue = incrementValue = 0 ? 1 : incrementValue //error - Assigning a variable to itself
        

        正确的是 - WITH SPACES 和 WITH ==

        incrementValue = incrementValue == 0 ? 1 : incrementValue //worked
        

        【讨论】:

          【解决方案4】:
              return episodes == nil ? .movie : .tvShow
          

          【讨论】:

          • 感谢您抽出宝贵时间回答!最好能解释一下你的答案,而不仅仅是代码。
          • 这不是答案。我标记了它,但 anusha.V 做得不好并且没有删除它。因此应标记并删除 anusha.V。
          猜你喜欢
          • 2012-11-19
          • 2018-12-22
          • 2012-10-01
          • 1970-01-01
          • 2015-09-21
          • 2021-09-07
          • 1970-01-01
          • 2017-01-01
          • 2013-12-22
          相关资源
          最近更新 更多