Exponentiation in Swift | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
+ 4

Exponentiation in Swift

I need to perform exponentiation in Swift (done with the ** in python and javascript) but there is no such operator. Google said I need to use ā€œpow(a, b)ā€ instead of ā€œa ** bā€, but ā€œerror: use of unresolved identifier powā€. More google searching said I need to do ā€œimport Darwinā€ to get access to pow and other math functions. Guess what: ā€œerror: no module Darwinā€. Help!

12th Sep 2019, 5:37 AM
Jason Stone
Jason Stone - avatar
7 Respostas
+ 4
Maybe you can define your own power function, like this: func pow (base:Int, power:UInt) -> Int { var answer : Int = 1 for _ in 0..power { answer *= base } return answer } Copied from https://stackoverflow.com/questions/24196689/how-to-get-the-power-of-some-integer-in-swift-language I donā€™t know any Swift myself šŸ˜ŠšŸ˜Š
12th Sep 2019, 8:26 AM
marjel101
marjel101 - avatar
+ 5
import Foundation, then you can use pow(a,b).
12th Sep 2019, 5:51 AM
Crash
Crash - avatar
+ 4
Sorry, I do not know. I have not tried Swift on Sololearn yet. I tried Swift on my Mac some time ago.
12th Sep 2019, 6:05 AM
Crash
Crash - avatar
+ 2
so SL has foundation but not darwin? thatā€™s confusing
12th Sep 2019, 5:54 AM
Jason Stone
Jason Stone - avatar
+ 2
code: ā€œimport Foundationā€ result: <module-includes>:1:10: note: in file included from <module-includes>:1: #include "CoreFoundation.h" ^ ..\Playground\/CoreFoundation.h:25:10: error: 'assert.h' file not found #include <assert.h> ^ <unknown>:0: error: could not build C module 'CoreFoundation' <module-includes>:1:10: note: in file included from <module-includes>:1: #include "../../..../Playground/-w64-mingw32/include/assert.h" ^
12th Sep 2019, 5:57 AM
Jason Stone
Jason Stone - avatar
+ 2
yeah, I was thinking I might have to write it myself. All I really need is powers of two, so itā€™ll be simple.
12th Sep 2019, 2:09 PM
Jason Stone
Jason Stone - avatar
+ 1
Hello! To use the ā€œpow(_:,_:)ā€ Function, you need to import the Foundation module. Also, Swift enables you to define this functionality yourself; like in the following code: https://code.sololearn.com/c4iMv66GY8Tp/?ref=app
17th Jul 2021, 9:19 AM
Pawel Zabinski
Pawel Zabinski - avatar