It might be of interest as to why Swift yields an error here (not only how to avoid it).
As many error messages in Swift, the actual error of interest is obfuscated by other error messages, in this case the somewhat standard 'consecutive statments ...'
message. The core error here is, however, that there exists no unary (prefix) operator *
. The follow-up error, given the case where a unary prefix operator *
were to exist, is that the expression 'tempC *9/5+32'
would reduce to (assuming high precedence for this *
unary operator) 'tempC IL/5+32'
(IL
integer literal), which is naturally erroneous, much like an expression 'let a: Int = 1 1'
would be.
Now, unary prefix operators exists for e.g. +
and -
:
/* '+' and '-' unary (prefix) operators in action: OK */
let a : Int = 1 + -1 // 0, OK
let b : Int = +(-1) // -1, OK
let c : Int = -(-(-(-(-(-(1)))))) // 1, OK
let d : Int = *1 /* error: '*' is not a prefix unary operator */
Swift infers an operator to be unary if it appears immediately before its target and if no other operand appears immediately before itself. If it finds another operand immediately before itself, it infers the operator as binary. Take the following examples:
let e: Int = 1 + 1 // binary, OK
let f: Int = 1+1 // binary, OK
let g: Int = 1 +1 /* unary prefix: resulting expression 'let g: Int = 1 1' erroneous */
let h: Int = 1+ /* + not a postfix unary operator, erroneous */
See the Swift Language Guide - Basic Operators for details:
Unary operators operate on a single target (such as -a). Unary prefix
operators appear immediately before their target (such as !b), and
unary postfix operators appear immediately after their target (such as
i++).
The lesson here is to keep a keen eye out for expressions where operators are used in a unary prefix (or postfix) fashion unintendently, to avoid getting confused by obfuscated error messages from Swift.
Finally, note that we may naturally define our own prefix unary operators in case we find them to be missing
prefix operator * {}
prefix func * (rhs: Int) -> Int {
return rhs*rhs
}
let i : Int = *2 // 4, OK