Swift Introduction
Swift is a modern programming language for building apps for Apple devices.
What is Swift?
- Swift was created by Apple and released in 2014
- It replaced Objective-C as the main language for Apple apps
- It is open source, so it also runs on Linux and Windows
- It is designed to be safe: many errors are caught while you write code
What Can You Build?
| Platform | Examples |
|---|---|
| iPhone and iPad (iOS) | Shopping, banking and game apps |
| Mac (macOS) | Desktop tools and editors |
| Apple Watch | Fitness and health apps |
| Server | Web APIs with the Vapor framework |
How to Run Swift
- Xcode (free on the Mac App Store): choose File, New, Playground. A playground runs your code as you type.
- Swift Playgrounds app on iPad or Mac: friendly for beginners.
- Online compilers: search for "Swift online compiler" if you use Windows or Linux.
To publish apps on the App Store you need a Mac with Xcode. To learn the language itself, any of the options above is enough.
Your First Program
Example
swift
print("Hello, Workownix!")Output
Hello, Workownix!
That is a complete Swift program. There is no main function to write and no semicolon needed at the end of the line. Swift runs the code from top to bottom.
Printing Values
print() shows text and moves to a new line. You can print numbers, calculations and several values at once:
Example
swift
print("Karachi")
print(25 + 17)
print("Total:", 450, "rupees")
print("Loading", terminator: "")
print("...done")Output
Karachi 42 Total: 450 rupees Loading...done
- Values separated by commas are printed with a space between them.
terminator: ""stopsprintfrom adding a new line, so the next output continues on the same line.
Comments
Comments are notes in your code. Swift ignores them when running.
Example
swift
// A single-line comment
print("Comments are not shown") // a comment after code
/* A comment that
spans several lines */Output
Comments are not shown
Swift Syntax Rules
| Rule | Example |
|---|---|
| Swift is case-sensitive | name and Name are different |
| Strings use double quotes | "Lahore" |
| Semicolons are optional | Only needed for two statements on one line |
| Code blocks use curly braces | if x > 0 { ... } |
Exercise
Exercise
Which function prints text in Swift?
