Exponentiation in Swift | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita
+ 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 Respuestas
+ 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