Previously I worked with swift occasionally and using xCode only. There is my previous post with XML parser written in swift language. Here is my experience in swift installation on Linux platform with initial command line programming example.
The first step – swift installation:
It takes several minutes.
Check swift version:
# swift –version Swift version 5.3.3 (swift-5.3.3-RELEASE) Target: x86_64-unknown-linux-gnu |
Create simple program:
import Foundation let date = Date() print("Now: ", date) print("Hello, world!") |
Execute it in interpreter mode:
# swift helloworld.swift Now: 2021-03-02 17:38:47 +0000 Hello, world! |
Now let us create executable file built from swift sources. Create subdirectory, enter in this directory and generate the package with type executable:
# mkdir helloworld # cd helloworld/ # swift package init –type executable Creating executable package: helloworld Creating Package.swift Creating README.md Creating .gitignore Creating Sources/ Creating Sources/helloworld/main.swift Creating Tests/ Creating Tests/LinuxMain.swift Creating Tests/helloworldTests/ Creating Tests/helloworldTests/helloworldTests.swift Creating Tests/helloworldTests/XCTestManifests.swift |
The generated package project file name is Package.swift, also Sources/helloworld/main.swift file was created which is main project source file.
The main.switch file looks like:
print("Hello, world") |
Build and run:
# switch run helloworld -bash: switch: command not found # swift run helloworld [2/2] Linking helloworld Hello, world! |
The new executable file located at:
# ls -l ./.build/x86_64-unknown-linux-gnu/debug/helloworld -rwxr-xr-x. 1 root root 32048 Mar 3 13:22 ./.build/x86_64-unknown-linux-gnu/debug/helloworld |
Execute it:
# ./.build/x86_64-unknown-linux-gnu/debug/helloworld Hello, world! |
Now I want to add my helloworld.swift file to the project:
# cp ../helloworld.swift Sources/helloworld/ # ls Sources/helloworld/ helloworld.swift main.swift |
Building again. Ops! The compiler gives me errors:
# swift build –target helloworld /Alex/helloworld/Sources/helloworld/helloworld.swift:3:1: error: expressions are not allowed at the top level print("Now: ", date) ^ /Alex/helloworld/Sources/helloworld/helloworld.swift:4:1: error: expressions are not allowed at the top level print("Hello, world!") |
Changing the source files. For helloworld.swift wrap the code into class definition:
import Foundation class PrintingMessages { func printing(txt: String="Hello world!") { let date = Date() print("Now: ", date) print(txt) } } |
In main.cpp we create object of PrintingMessages class and cll printing function:
let printingMessages = PrintingMessages() printingMessages.printing(txt: "Hello something else!") |
Rebuild, link and run:
# swift build –target helloworld # swift run helloworld [2/2] Linking helloworld Now: 2021-03-03 20:49:38 +0000 Hello something else! # ./.build/x86_64-unknown-linux-gnu/debug/helloworld Now: 2021-03-03 20:49:52 +0000 Hello something else! |