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:29

If you happen to be raising 2 to some power, you can use the bitwise left shift operator:

let x = 2 << 0    // 2
let y = 2 << 1    // 4
let z = 2 << 7    // 256

Notice that the 'power' value is 1 less than you might think.

Note that this is faster than pow(2.0, 8.0) and lets you avoid having to use doubles.

查看更多
再贱就再见
3楼-- · 2019-01-22 17:35

If you're specifically interested in the exponentiation operator for Int type, I don't think that existing answers would work particularly well for large numbers due to the way how floating point numbers are represented in memory. When converting to Float or Double from Int and then back (which is required by pow, powf and powl functions in Darwin module) you may lose precision. Here's a precise version for Int:

let pow = { Array(repeating: $0, count: $1).reduce(1, *) }

Note that this version isn't particularly memory efficient and is optimized for source code size.

Another version that won't create an intermediate array:

func pow(_ x: Int, _ y: Int) -> Int {
  var result = 1
  for i in 0..<y {
    result *= x
  }
  return result
}
查看更多
登录 后发表回答