Menu
Coddy logo textTech

Struct or Class

Part of the Object Oriented Programming section of Coddy's Swift journey. Lesson 10 of 57.

Swift's guideline is to start with a struct and choose a class only when you need what only classes offer. Structs are simpler: every variable owns its own value, so a change in one place never surprises code somewhere else.

struct Temperature {
    var celsius: Double
}

var today = Temperature(celsius: 21)
var yesterday = today
yesterday.celsius = 18
print(today.celsius)

Output:

21.0

Choose a class when one object must be shared: several parts of the program need to see the same changing state, such as one bank account used by many screens. Classes also support inheritance, which structs do not.

class SharedLog {
    var lines: [String] = []
}

let log = SharedLog()
let moduleA = log
let moduleB = log
moduleA.lines.append("A started")
moduleB.lines.append("B started")
print(log.lines.count)

Output:

2

Structs can get == for free. Add Equatable to the declaration and Swift compares every property; classes compare identity with === instead:

struct Point: Equatable {
    var x: Int
    var y: Int
}

print(Point(x: 1, y: 2) == Point(x: 1, y: 2))
print(Point(x: 1, y: 2) == Point(x: 2, y: 1))

Output:

true
false

A quick check: if two items with the same data should count as the same thing, use a struct (a point, a price, a date). If an item has an identity that matters even when its data matches another one (a user account, an open file), use a class.

struct Money { var cents: Int }          // 500 cents is 500 cents
class UserAccount {                      // two accounts can share a name
    let id: Int
    var name: String
    init(id: Int, name: String) { self.id = id; self.name = name }
}
challenge icon

Challenge

Easy

Point is a struct that should be comparable with ==. Add the conformance and complete countDistinct(_:), which returns how many different points are in the list (two points are the same when both coordinates match).

The supplied code reads one point per line as x,y and prints distinct: with the count.

Your code goes in Point.swift and Functions.swift. main.swift holds the supplied input/output code and cannot be edited.

Try it yourself

// Supplied input/output code: keep it as it is
var input: [String] = []
while let line = readLine() { input.append(line) }
let points = input.map { line -> Point in
    let p = line.split(separator: ",").map { Int($0)! }
    return Point(x: p[0], y: p[1])
}
print("distinct: \(countDistinct(points))")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming

Practice on your own: Swift playground