I'm learning swift recently, but I have a basic problem that can't find an answer
I want to get something like
var a:Int = 3
var b:Int = 3
println( pow(a,b) ) // 27
but the pow function can work with double number only, it doesn't work with integer, and I can't even cast the int to double by something like Double(a) or a.double()...
Why it doesn't supply the power of integer? it will definitely return an integer without ambiguity ! and Why I can't cast a integer to a double? it just change 3 to 3.0 (or 3.00000... whatever)
if I got two integer and I want to do the power operation, how can I do it smoothly?
Thanks!
If you like, you could declare an infix
operator
to do it.
// Put this at file level anywhere in your project
infix operator ^^ { associativity left precedence 160 }
func ^^ (radix: Int, power: Int) -> Int {
return Int(pow(Double(radix), Double(power)))
}
// ...
// Then you can do this...
let i = 2 ^^ 3
// ... or
println("2³ = \(2 ^^ 3)") // Prints 2³ = 8
I used two carets so you can still use the XOR operator.
Update for Swift 3
In Swift 3 the "magic number" precedence
is replaced by precedencegroups
:
precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence }
infix operator ^^ : PowerPrecedence
func ^^ (radix: Int, power: Int) -> Int {
return Int(pow(Double(radix), Double(power)))
}
// ...
// Then you can do this...
let i2 = 2 ^^ 3
// ... or
print("2³ = \(2 ^^ 3)") // Prints 2³ = 8
So if you wanted to do this for Floats, would you do this: infix operator ^^ { } func ^^ (radix: Float, power: Float) -> Float { return Float(pow(Double(radix), Double(power))) }
func ^^ (radix: Double, power: Double) -> Double { return Double(pow(Double(radix), Double(power))) }
I found this didn't quite behave as I expected because the precedence was off. For an exponentiative operator, set precedence to 160 (see developer.apple.com/library/ios/documentation/Swift/Conceptual/… and developer.apple.com/library/ios/documentation/Swift/Conceptual/…) like so:
infix operator ^^ { precedence 160 } func ^^
... and so onI really like this solution, but with Swift 3 it does not work. Any idea how to make it work?
func p(_ b: Bool) -> Double { return b?-1:1 }
?