Swift ternary syntax error

假装没事ソ 提交于 2020-03-16 07:35:21

问题


I used to program in Objective-C all the time and I am new to Swift. This error Xcode gives me really confuse me.

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

On this line I intended to use ternary. leftTopIndex and rightTopIndex are both Int type. However Xcode gives me those on this particular line,

Consecutive statements on a line must be separated by ';' Expected expression

Can anybody tell me what those mean? Thanks.


回答1:


Swift error messages are frequently cryptic and not helpful. Your real problem is that Swift needs some space around the ? and :.

var topViewIndexForIndexAdjust = ifLeft ? leftTopIndex : rightTopIndex



回答2:


You must use blanks to separate operands and operators:

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

Swift is very strict on that - even this apparently correct line of code:

let val =12

generates a compilation error.




回答3:


Struggled with the cryptic Swift error messages for Ternary operators

Error 1

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

Error 2

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

Correct one is - WITH SPACES and WITH ==

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


来源:https://stackoverflow.com/questions/28919408/swift-ternary-syntax-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!