Robert
Robert

Reputation: 153

How can I run/call a python script while using swift?

I am trying to make an iOS app that will calculate pi to a set about of decimal places based on what the user wants. I currently have a python script that will take in an integer value from the user and then use that in the calculation of Pi. I also have a swift/Xcode project that will only allow a user to input an integer value. So I am wondering if there is a way for me to pass this value that the user enters from a textbox in my swift project to then give that to the python code, run it, and then output the result? In my python code, I am using "timer" to be able to calculate the time it takes to calculate pi to the set digits that was requested. So I would only need to be able to display this result.

I have thought about rewriting the python script into swift, but I am unsure of how to do that. This is the definition I am using in my python script to calculate pi:

def pi():
decimal.getcontext().prec += 2
three = decimal.Decimal(3)
first, second, third, forth, fifth, sixth, numb = 0, three, 1, 0, 0, 24, 3 
while numb != first:
    first = numb
    third, forth = third + forth, forth + 8
    fifth, sixth = fifth + sixth, sixth + 32
    second = (second * third) / fifth
    numb += second
decimal.getcontext().prec -= 2
return +numb

But I was unsure of how to rewrite this into swift language, so I figured getting swift to pass the precision value into python would be easier.

Upvotes: 0

Views: 2878

Answers (1)

Renzo Tissoni
Renzo Tissoni

Reputation: 759

You definitely can run Python code in Swift since Python is designed to be embedded and has a C interface API. Check how Swift for TensorFlow uses Python interoperability (although I couldn't find a quick way to only use that module and not the whole TensorFlow). You can also check PythonKit out.

However, I don't think rewriting that script would be too difficult, and it might be better to avoid more libraries and dependencies in your project.

Edit: As Joakim Danielson pointed out, you'll need the Python runtime, and it doesn't seem to be available in iOS, so you seem to be limited to macOS for this.

Upvotes: 1

Related Questions