Swift provides an interactive Read Eval Print Loop (REPL), which is accessed by typing swift at the command prompt.

$ swift
Welcome to Swift version 5.2.2 (swift-5.2.2-RELEASE).
Type :help for assistance.

Lets try a new feature from the latest version of Swift. We can see what is new in Swift from the Revision History. One interesting new feature for Swift 5.2 is callAsFunction, which “lets instances of classes, structures, and enumerations be used with function call syntax”. Lets try this in the REPL with a struct.

$ swift
Welcome to Swift version 5.2.2 (swift-5.2.2-RELEASE).
Type :help for assistance.
1> struct Hello {
2.     func callAsFunction(_ name: String) {
3.         print("Hello, \(name)")
4.     }
5. }

You can enter blocks of code into the REPL e.g. structs, classes & enumerations and the Swift compiler will wait for more input (or you can paste blocks).

6> let hello = Hello()
hello: Hello = {}
(Hello) = {}

Once the hello variable has been created, it can be invoked using the new functionality, or can be invoked the usual way.

7> hello("Swift!") // Call as function
Hello, Swift!
8> hello.callAsFunction("Swift!") // Call as usual
Hello, Swift!
9> :q

Use :q to exit the REPL.

Written by Mark Brownsword

I've been working as an enterprise developer for more than 15 years, always using .NET platform and recently building for iOS with Swift. My degree is in Business Studies, majoring in information systems, where I learnt the fundamentals of software engineering for building systems for business.