如何获得一些整数在Swift语言的力量?
发布时间:2020-12-14 06:07:41 所属栏目:百科 来源:网络整理
导读:我最近学习swift,但我有一个基本的问题,找不到答案 我想得到一些东西 var a:Int = 3var b:Int = 3 println( pow(a,b) ) // 27 但pow函数只能使用双数,它不能与整数工作,我甚至不能通过double(a)或a.double()…等类型转换int double。 为什么它不提供整数
我最近学习swift,但我有一个基本的问题,找不到答案
我想得到一些东西 var a:Int = 3 var b:Int = 3 println( pow(a,b) ) // 27 但pow函数只能使用双数,它不能与整数工作,我甚至不能通过double(a)或a.double()…等类型转换int double。 为什么它不提供整数的幂?它肯定会返回一个整数没有歧义! 如果我有两个整数,我想做电源操作,我怎么能做到顺利? 谢谢!
如果你喜欢,你可以声明一个中缀操作符来做。
// 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("23 = (2 ^^ 3)") // Prints 23 = 8 我使用了两个插入符号,所以你仍然可以使用XOR operator。 Swift 3的更新 在Swift 3中,“magic number”优先级被替换为precedencegroups: precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence } infix operator ^^ : PowerPrecedence func ^^ (radix: Int,Double(power))) } // ... // Then you can do this... let i2 = 2 ^^ 3 // ... or print("23 = (2 ^^ 3)") // Prints 23 = 8 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |