Learn the Basics of Swift in Less than 10 Minutes

Swift is a powerful and intuitive programming language for iOS, macOS, watchOS, and tvOS. It‘s designed to give developers more freedom than ever. Swift is easy to use and open source, so anyone with an idea can create something incredible.

In this crash course, we‘ll cover the fundamentals of Swift and get you up and running as quickly as possible. Whether you‘re a seasoned developer looking to dive into mobile app development or completely new to programming, by the end of this guide, you‘ll have a solid understanding of Swift‘s key features and concepts.

What is Swift?

Swift is a general-purpose, multi-paradigm, compiled programming language developed by Apple Inc. for iOS, macOS, watchOS, tvOS, Linux and z/OS. It‘s designed to work with Apple‘s Cocoa and Cocoa Touch frameworks and the large body of existing Objective-C code written for Apple products.

Swift was introduced at Apple‘s 2014 Worldwide Developers Conference (WWDC). It underwent an upgrade to version 1.2 during 2014 and a more major upgrade to Swift 2 at WWDC 2015. Initially a proprietary language, version 2.2 was made open-source software under the Apache License 2.0 on December 3, 2015, for Apple‘s platforms and Linux.

Swift‘s Growing Popularity

Since its release, Swift has seen widespread adoption and support from the developer community. According to the TIOBE Index, which measures the popularity of programming languages, Swift is currently the 9th most popular language as of January 2023.

TIOBE Index - Swift Popularity

In Stack Overflow‘s 2022 Developer Survey, Swift ranked as the 6th most loved programming language, with 65.5% of developers expressing interest in continuing to develop with it.

These statistics demonstrate that Swift has rapidly become a mainstream language and a key skill for mobile app developers.

Swift Language Basics

Now let‘s dive into the core concepts and syntax of the Swift language.

Variables and Constants

One of the most fundamental concepts in programming is the ability to store and manipulate data using variables. In Swift, there are two ways to declare variables:

var x = 5 
let y = 10

The var keyword declares a mutable variable, meaning its value can be changed. The let keyword declares a constant — a value that cannot be changed once it is set.

Here‘s a more concrete example:

var score = 0 // Variable 
score = 50
print(score) // Prints: 50

let maxScore = 100 // Constant
maxScore = 200 // Error: Cannot assign to ‘let‘ value ‘maxScore‘

Type Inference and Annotation

Swift is a type-safe language, which means every variable must have a specific type (like Int or String) and can only hold values of that type. However, Swift also has a powerful type inference system. In many cases, Swift can determine the type of a variable automatically based on the initial value you provide.

let message = "Hello, world!" // Inferred to be of type String
let score = 100 // Inferred to be of type Int

You can also explicitly specify the type of a variable using type annotation:

let message: String = "Hello, world!"
let score: Int = 100
let pi: Double = 3.14159

Type inference makes code cleaner and less repetitive while still maintaining type safety.

Basic Data Types

Swift provides a rich set of built-in data types, including:

  • Int: Whole numbers, such as -1, 0, 1, 2, etc.
  • Double and Float: Numbers with a fractional component, such as 3.14159.
  • Bool: Boolean values of either true or false.
  • String: Textual data.
  • Character: A single Unicode character.
  • Optional: A special type that can hold either a value or no value (nil).

Here are some examples:

let age: Int = 30
let price: Double = 12.99
let isAvailable: Bool = true
let message: String = "Good morning!"
let letter: Character = "A"
let optionalString: String? = "Hello"

Printing and String Interpolation

To print output to the console in Swift, you use the print() function:

let name = "Alice"
print("Hello, " + name) // Prints: Hello, Alice

Swift also supports string interpolation, which allows you to construct a string from a mix of constants, variables, literals, and expressions by including their values inside a string literal. Each item that you insert into the string literal is wrapped in a pair of parentheses, prefixed by a backslash (\).

let name = "Alice"
let age = 25
print("My name is \(name) and I‘m \(age) years old.") 
// Prints: My name is Alice and I‘m 25 years old.

Collection Types

Swift provides three primary collection types, each of which stores collections of values.

Arrays

An array stores values of the same type in an ordered list. You create an array by placing a list of values of the same type, separated by commas, inside square brackets:

let evenNumbers = [2, 4, 6, 8]
var students = ["Alice", "Bob", "Charlie"]

You can access and modify array elements using square bracket syntax:

print(students[0]) // Prints: "Alice"
students[1] = "David"
print(students[1]) // Prints: "David"

Dictionaries

A dictionary stores associations between keys of the same type and values of the same type in a collection with no defined ordering. Each value is associated with a unique key, which acts as an identifier for that value within the dictionary.

var scores = ["Alice": 90, "Bob": 85, "Charlie": 95]

You can access values in the dictionary using square bracket syntax, specifying the key:

print(scores["Alice"]) // Prints: 90 (Optional)
scores["Bob"] = 92
print(scores["Bob"]) // Prints: 92 (Optional)

Sets

A set stores distinct values of the same type in a collection with no defined ordering. You can create a set by placing a list of values of the same type, separated by commas, inside braces:

let colors: Set<String> = ["red", "green", "blue"]

Sets are useful when you need to ensure that an item only appears once and the order of items doesn‘t matter.

Control Flow

Swift provides several ways to control the flow of execution in your code, including conditional statements and loops.

If/Else

An if statement allows you to conditionally execute code based on the evaluation of one or more conditions. You can provide an optional else clause that‘s executed when the condition is false.

let score = 85

if score >= 90 {
    print("Excellent!")
} else if score >= 80 {
    print("Good job!")
} else {
    print("Keep trying!")
}
// Prints: "Good job!"

Switch

A switch statement considers a value and compares it against several possible matching patterns. It then executes an appropriate block of code, based on the first pattern that matches successfully.

let grade = "B"

switch grade {
case "A":
    print("Excellent!")
case "B", "C":
    print("Well done")
case "D":
    print("You passed")
case "F":
    print("Better luck next time")
default:
    print("Invalid grade")
}
// Prints: "Well done"

Loops

Swift provides three main types of loops: for-in, while, and repeat-while.

The for-in loop performs a set of statements for each item in a sequence, such as ranges of numbers, items in an array, or characters in a string.

let count = 5
for i in 1...count {
    print("\(i) times 5 is \(i * 5)")
}

The while loop performs a set of statements until a condition becomes false.

var i = 1
while i <= 5 {
    print(i)
    i += 1
}

The repeat-while loop is similar to a while loop, except that it checks the condition after the loop has run, ensuring that the loop will be run at least once.

var i = 1
repeat {
    print(i)
    i += 1
} while i <= 5

Functions and Closures

Functions are self-contained chunks of code that perform a specific task. You define a function with the func keyword, followed by the function‘s name, input parameters, return type, and the code in the function body.

func greet(person: String) -> String {
    return "Hello, " + person + "!"
}

print(greet(person: "John")) // Prints: "Hello, John!"

Functions are a crucial building block in Swift, allowing you to break your code into smaller, reusable pieces.

Closures are self-contained blocks of functionality that can be passed around and used in your code. They are similar to functions, but they can capture and store references to any constants and variables from the context in which they are defined.

let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]

let sortedNames = names.sorted(by: { (s1: String, s2: String) -> Bool in
    return s1 < s2
})

print(sortedNames) // Prints: ["Alex", "Barry", "Chris", "Daniella", "Ewa"]

Object-Oriented Programming

Swift is a protocol-oriented programming language that also supports object-oriented concepts like classes, inheritance, and polymorphism.

Classes and Structs

Classes and structures are general-purpose, flexible constructs that become the building blocks of your program‘s code. You define properties and methods to add functionality to your classes and structures by using the same syntax you use to define constants, variables, and functions.

Here‘s an example of a simple class:

class Shape {
    var numberOfSides = 0
    func simpleDescription() -> String {
        return "A shape with \(numberOfSides) sides."
    }
}

var shape = Shape()
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription()

Structs are similar to classes, but they are value types (copied when they are assigned to a variable or constant, or when they are passed to a function) rather than reference types.

struct Point {
    var x = 0.0, y = 0.0
}
let origin = Point(x: 0.0, y: 0.0)

Protocols

A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements.

protocol ExampleProtocol {
    var simpleDescription: String { get }
    mutating func adjust()
}

class SimpleClass: ExampleProtocol {
    var simpleDescription: String = "A very simple class."
    var anotherProperty: Int = 69105
    func adjust() {
        simpleDescription += "  Now 100% adjusted."
    }
}

Protocols are a key feature in Swift that allow you to define contracts that can be adopted by multiple types, enabling powerful abstractions and polymorphism.

Error Handling

Error handling is the process of responding to and recovering from error conditions in your program. Swift provides first-class support for throwing, catching, propagating, and manipulating recoverable errors at runtime.

Here‘s a simple example:

enum PrinterError: Error {
    case outOfPaper
    case noToner
    case onFire
}

func send(job: Int, toPrinter printerName: String) throws -> String {
    if printerName == "Never Has Toner" {
        throw PrinterError.noToner
    }
    return "Job sent"
}

do {
    let printerResponse = try send(job: 1040, toPrinter: "Never Has Toner")
    print(printerResponse)
} catch PrinterError.onFire {
    print("I‘ll just put this over here, with the rest of the fire.")
} catch let printerError as PrinterError {
    print("Printer error: \(printerError)")
} catch {
    print(error)
}
// Prints: "Printer error: noToner"

Using Swift on the Server

While Swift is primarily known for iOS and macOS development, it‘s also gaining traction as a server-side language. Frameworks like Vapor and Kitura allow you to build web applications and APIs entirely in Swift.

Here‘s a simple example of a Vapor route:

import Vapor

let app = try Application()
let routes = app.routes

routes.get("hello") { req in
    return "Hello, world!"
}

try app.run()

This creates a simple HTTP endpoint that returns "Hello, world!" when accessed.

Server-side Swift opens up exciting possibilities, allowing you to share code and leverage your existing Swift skills on the backend.

Best Practices and Pro Tips

Here are a few best practices and pro tips to keep in mind as you‘re learning and using Swift:

  1. Use meaningful names: Choose clear, descriptive names for your variables, constants, functions, and types. This makes your code more readable and self-documenting.

  2. Leverage type inference: While it‘s good to know how to explicitly declare types, make use of Swift‘s type inference capabilities to write cleaner, less repetitive code.

  3. Prefer constants over variables: Use let to declare constants wherever possible. Only use var when you know the value of a variable will change. This makes your intent clearer and can help prevent accidental changes.

  4. Embrace optionals: Optionals are a powerful feature in Swift. Use them to represent values that may or may not be present, and unwrap them safely to avoid crashes.

  5. Handle errors gracefully: Use Swift‘s error handling capabilities to gracefully handle and recover from error conditions. This leads to more robust, reliable code.

Conclusion

Congratulations! You‘ve learned the basics of Swift in less than 10 minutes. We‘ve covered a lot of ground, including:

  • Variables and constants
  • Type inference and basic data types
  • Collection types (arrays, dictionaries, sets)
  • Control flow with conditionals and loops
  • Functions and closures
  • Object-oriented programming with classes and structs
  • Protocols and error handling
  • Using Swift for server-side development

This is just the beginning of your Swift journey. To continue learning, I recommend:

Remember, the best way to learn is by doing. Start a project, experiment with the language, and don‘t be afraid to make mistakes. Swift has a vibrant, supportive community, so don‘t hesitate to reach out for help when you need it.

Happy coding!

Similar Posts