Search code examples
swiftread-eval-print-loop

How to reset the Swift REPL?


enter image description here

As you know once installed XCode you can obtain a REPL by just typing $swift on the terminal. Then you can copy&paste your code:

func isEven(number: Int) -> Bool {
  return number % 2 == 0
}
let evens = Array(1...10).filter(isEven)
print(evens)

and you obtain a result ([2, 4, 6, 8, 10]) in this case. But how do you "reset" the session in order to start with a clean state? One option is exit the session with :q and enter again. There is a better way?


Solution

  • After you mention the use of Swift REPL in classes I thought maybe you'll get satisfied with such a dirty trick:

    $ while true; do swift; done
    Welcome to Apple Swift version 2.2 (swiftlang-703.0.18.8 clang-703.0.30). Type :help for assistance.
      1> let x = 1
    x: Int = 1
      2> x
    $R0: Int = 1
      3> :q
    Welcome to Apple Swift version 2.2 (swiftlang-703.0.18.8 clang-703.0.30). Type :help for assistance.
      1> x
    repl.swift:1:1: error: use of unresolved identifier 'x'
    x
    ^
    
      1> :q
    Welcome to Apple Swift version 2.2 (swiftlang-703.0.18.8 clang-703.0.30). Type :help for assistance.
      1> ^D
    ^C
    $
    

    Full quit is possible by quickly pressing ^D (EOF; to terminate the REPL) then ^C (to terminate the loop).