Exponentiation operator in Swift

2019-01-22 17:00发布

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?

8条回答
贼婆χ
2楼-- · 2019-01-22 17:10

There isn't one but you have the pow function.

查看更多
成全新的幸福
3楼-- · 2019-01-22 17:11

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
查看更多
ら.Afraid
4楼-- · 2019-01-22 17:17

For anyone looking for a Swift 3 version of the ** infix operator:

precedencegroup ExponentiationPrecedence {
  associativity: right
  higherThan: MultiplicationPrecedence
}

infix operator ** : ExponentiationPrecedence

func ** (_ base: Double, _ exp: Double) -> Double {
  return pow(base, exp)
}

func ** (_ base: Float, _ exp: Float) -> Float {
  return pow(base, exp)
}

2.0 ** 3.0 ** 2.0    // 512
(2.0 ** 3.0) ** 2.0  // 64
查看更多
爷、活的狠高调
5楼-- · 2019-01-22 17:22

Like most of the C-family of languages, there isn't one.

查看更多
该账号已被封号
6楼-- · 2019-01-22 17:26

An alternative answer is to use NSExpression

let mathExpression = NSExpression(format:"2.5**2.5")
let answer = mathExpression.expressionValue(with: nil, context: nil) as? Double

or

let mathExpression = NSExpression(format:"2**3")
let answer = mathExpression.expressionValue(with: nil, context: nil) as? Int
查看更多
一纸荒年 Trace。
7楼-- · 2019-01-22 17:28

I did it like so:

operator infix ** { associativity left precedence 200 }

func ** (base: Double, power: Double) -> Double {
    return exp(log(base) * power)
}
查看更多
登录 后发表回答