Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing Swift code embedded into one line terminal command

I know there is the Swift REPL and the Xcode playgrounds, but I wonder whether there is an alternative to ruby -e "<code>" or sh -c "<code>" in Swift where the given one line code would be executed as the result of the command?

like image 366
Lukas Kubanek Avatar asked Oct 16 '25 14:10

Lukas Kubanek


2 Answers

There isn't a direct equivalent (you can ask the swift command for its options with swift --help and see there's nothing like Ruby's -e).

But there's a workaround.

You can pass a Swift expression to the compiler direclty using echo and | (the "pipe") like this:

echo "print(42)" | swift

Result:

Welcome to Apple Swift version 2.1.1 ("700.1.101.9 700.1.78"). Type :help for assistance.
42

I guess it's similar to the behavior you were looking for.

We notice that it always prints the introduction sentence, but there's a way to fix this, by adding - at the end of the command, like this:

echo "print(42)" | swift -

Result:

42

When using literal strings, escape the double quotes:

echo "print(\"hello\")" | swift -

Result:

hello

You can execute any expression, even loops:

echo "for num in 1...5 { print(num) }" | swift -

Result:

1
2
3
4
5

etc.

It's still the REPL so it will give feedback about variables (omitting the - trick at the end), for example:

echo "let x = 42;print(x)" | swift

Result:

Welcome to Apple Swift version 2.1.1 ("700.1.101.9 700.1.78"). Type :help for assistance.
42
x: Int = 42

like image 198
Eric Aya Avatar answered Oct 18 '25 10:10

Eric Aya


As of Swift version 5.8, you can now runs code directly from the command line with swift -e

bash-3.2$ swift --help | grep -e "-e "
  -e <value>              Executes a line of code provided on the command line
bash-3.2$ swift -e 'print("fofo")'
fofo
bash-3.2$ swift -e 'import Foundation ; var users = ["zoe", "joe", "albert", "james"] ; for user in users {  print(user) }'
zoe
joe
albert
james
bash-3.2$
like image 35
byaruhaf Avatar answered Oct 18 '25 09:10

byaruhaf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!