✖️a^^n
問:Swift 現在是不是有 **
運算❓
// custom precedence
precedencegroup PowerPrecedence {
higherThan : MultiplicationPrecedence
associativity: right
}
// custom operator
infix operator ^^ : PowerPrecedence
extension Int {
/// `a^^n`: a to the n-th power
public static func ^^(a:Int, n:Int) -> Int {
precondition(n >= 0, "❌ 目前無法計算負的次方")
guard n > 0 else { return 1 }
return (1...n).reduce(1) { (product, i) in
product * a
}
}
}
Last updated
Was this helpful?