Swift Tutorial menu

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?

PlatformExamples
iPhone and iPad (iOS)Shopping, banking and game apps
Mac (macOS)Desktop tools and editors
Apple WatchFitness and health apps
ServerWeb APIs with the Vapor framework

How to Run Swift

  1. Xcode (free on the Mac App Store): choose File, New, Playground. A playground runs your code as you type.
  2. Swift Playgrounds app on iPad or Mac: friendly for beginners.
  3. 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: "" stops print from 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

RuleExample
Swift is case-sensitivename and Name are different
Strings use double quotes"Lahore"
Semicolons are optionalOnly needed for two statements on one line
Code blocks use curly bracesif x > 0 { ... }

Exercise

Exercise

Which function prints text in Swift?

Learn Swift with a teacher

Join the App Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp