4

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?

0

2 Answers 2

7

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

Sign up to request clarification or add additional context in comments.

Comments

1

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$

1 Comment

This seems to be the correct answer starting with Swift 5.8.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.