I just typed the following into a Swift switch statement:
var powerResult: Int = (7 ^ 9)
In the results panel, I get 14, which is not what I intended. What mistake am I making here?
EDIT: I'm trying to get 7 to the 9th power.
I just typed the following into a Swift switch statement:
var powerResult: Int = (7 ^ 9)
In the results panel, I get 14, which is not what I intended. What mistake am I making here?
EDIT: I'm trying to get 7 to the 9th power.
The ^
caret operator on Int
is for bitwise XOR, not exponentiation. Swift doesn't have a built-in standard library operator or method for this — which frankly seems like a bit of an oversight — so you have to use the C function pow(_: Double, _: Double)
(you need to import Foundation
to access this, which will transitively import Darwin
or Glibc
.)
Thank you, I typed the following (into Swift Playgrounds) and it seems t work properly finally:
var powerResult = pow(Double(num1), Double(num2))
Thank you.