swiftoperatorsexponentiation

Exponentiation operator in Swift


I don't see an exponentiation operator defined in the base arithmetic operators in the Swift language reference.

Is there really no predefined integer or float exponentiation operator in the language?


Solution

  • There isn't an operator but you can use the pow function like this:

    return pow(num, power)
    

    If you want to, you could also make an operator call the pow function like this:

    infix operator ** { associativity left precedence 170 }
    
    func ** (num: Double, power: Double) -> Double{
        return pow(num, power)
    }
    
    2.0**2.0 //4.0