Contents

About Swift Syntax 1 (Declarations)

   Jan 15, 2024     1 min read

About “Swift syntax 1 (declarations)”

I recently had the opportunity to learn iOS and I’ve been working on the grammar, so I thought I’d write a post to summarize it.

As with any language, there are many different types of declarations.

Let’s take a look at them with some examples

Variable declarations (var)

Used to store values, and can be reassigned.

var name = "John"

Declaring a constant (let)

Used to store a value, which cannot be reassigned.

let pi :3.14159265

Function declarations (func)

Used to define the behavior of code.

func add(a: Int, b: Int) -> Int {
    return a + b
}

Class declaration (class)

Defines a class in object-oriented programming.

class Dog {
    var name: String
    init(name: String) {
        self.name = name
    }
}

Struct declaration (struct)

Used to define a value type.

struct Point {
    var x: Double
    var y: Double
}

Declaring an enumeration (enum)

Defines a group of related values.

enum Direction {
    case north
    case south
    case east
    case west
}

Protocol declarations (protocol)

Used to define specific requirements.

protocol CanFly {
    func fly()
}

Declaring an extension (extension)

Adds new functionality to an existing type.

extension Int {
    var squared: Int {
        return self * self
    }
}

Declaring type aliases (typealias)

Provide new names for existing types.

typealias Length = Double