Contact
do not contact us
# Swift Command Line Basics
## Running a Swift Script
```bash
swift myscript.swift # run directly
chmod +x myscript.swift && ./myscript.swift # make executable (needs shebang)
```
Add this shebang as the first line to run as `./script.swift`:
```swift
#!/usr/bin/swift
```
---
## Printing
```swift
print("Hello, world!")
print("Value:", 42)
print("No newline", terminator: "") // like echo -n
print("A", "B", "C", separator: ", ") // prints: A, B, C
```
---
## Variables
```swift
var name = "Alice" // mutable
let age = 30 // constant (like final)
var score: Double = 9.5 // explicit type
name = "Bob" // ok
// age = 31 // error - let is immutable
```
Common types: `String`, `Int`, `Double`, `Bool`, `[String]` (array)
---
## String Interpolation
```swift
let city = "Paris"
let pop = 2_100_000
print("City: \(city), population: \(pop)")
print("2 + 2 = \(2 + 2)")
```
---
## Command Line Arguments
```swift
let args = CommandLine.arguments
// args[0] is always the script name
print("Script:", args[0])
if args.count > 1 {
print("First arg:", args[1])
} else {
print("No arguments provided")
}
// Loop all args (skip script name)
for arg in args.dropFirst() {
print("Arg:", arg)
}
```
Run: `swift script.swift foo bar` → args = `["script.swift", "foo", "bar"]`
---
## User Input
```swift
print("Enter your name: ", terminator: "")
if let input = readLine() {
print("Hello, \(input)!")
}
```
---
## Conditionals
```swift
let x = 10
if x > 5 {
print("big")
} else if x == 5 {
print("five")
} else {
print("small")
}
```
---
## Loops
```swift
// Range loop
for i in 1...5 {
print(i)
}
// Array loop
let fruits = ["apple", "banana", "cherry"]
for fruit in fruits {
print(fruit)
}
// While
var count = 0
while count < 3 {
print(count)
count += 1
}
```
---
## Functions
```swift
func greet(name: String) -> String {
return "Hello, \(name)!"
}
print(greet(name: "Alice"))
// No return value
func sayHi() {
print("Hi!")
}
```
---
## String Operations
```swift
var s = " Hello, World! "
s.uppercased() // " HELLO, WORLD! "
s.lowercased()
s.trimmingCharacters(in: .whitespaces) // "Hello, World!"
s.contains("World") // true
s.replacingOccurrences(of: "World", with: "Swift")
s.hasPrefix("Hello")
s.hasSuffix("!")
s.split(separator: ",") // [" Hello", " World! "]
```
---
## Running Shell Commands
```swift
import Foundation
func shell(_ cmd: String) -> String {
let task = Process()
let pipe = Pipe()
task.standardOutput = pipe
task.executableURL = URL(fileURLWithPath: "/bin/bash")
task.arguments = ["-c", cmd]
try? task.run()
task.waitUntilExit()
return String(data: pipe.fileHandleForWriting.availableData, encoding: .utf8) ?? ""
}
let result = shell("ls -la")
print(result)
```
---
## Exit Codes
```swift
import Foundation
guard CommandLine.arguments.count > 1 else {
print("Usage: script.swift ")
exit(1) // non-zero = error
}
exit(0) // success
```