问题
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