Structs
Part of the Object Oriented Programming section of Coddy's Swift journey. Lesson 7 of 57.
A struct groups data and methods like a class. Swift writes a memberwise initializer for every struct, with one parameter per property, so a struct needs no init of its own:
struct Point {
var x: Int
var y: Int
func distanceFromOrigin() -> Int {
abs(x) + abs(y)
}
}
let p = Point(x: 3, y: -4)
print(p.x)
print(p.distanceFromOrigin())Output:
3
7Properties with default values can be left out of the memberwise initializer:
struct Settings {
var volume = 5
var muted = false
}
let quiet = Settings(volume: 1)
print(quiet.volume)
print(quiet.muted)Output:
1
falseA struct stored in a let constant cannot change at all, not even its var properties. Store it in a var to change it:
let fixed = Point(x: 1, y: 2)
// fixed.x = 5 // error: cannot assign, fixed is a let constant
var moving = Point(x: 1, y: 2)
moving.x = 5 // fineMany of Swift's own types are structs: Int, Double, String, Array and Dictionary. Your structs behave the same way as those types: they are plain values.
struct Money {
var cents: Int
func formatted() -> String {
"\(cents / 100).\(cents % 100 < 10 ? "0" : "")\(cents % 100)"
}
}
print(Money(cents: 1250).formatted())
print(Money(cents: 305).formatted())Output:
12.50
3.05Challenge
EasyDeclare a struct Item with the properties name (String), price (Int, in cents) and quantity (Int). Add a method total() that returns price times quantity, and a method line() that returns 2 x tea = 350.
The supplied code reads one item per line as name,price,quantity, creates each Item with the memberwise initializer and prints line(). It then prints sum: and the sum of all totals.
Your code goes in Item.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) }
var sum = 0
for row in input {
let p = row.split(separator: ",").map(String.init)
let item = Item(name: p[0], price: Int(p[1])!, quantity: Int(p[2])!)
print(item.line())
sum += item.total()
}
print("sum: \(sum)")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Classes and Objects
Working With FilesDefining ClassesMethods and selfInitializersClasses Are ReferencesRecap - Library Card4Encapsulation
Access ControlRead-Only From OutsideGuarding StateFailable InitializersRecap - Bank Account7Polymorphism and Generics
PolymorphismType CastingGeneric FunctionsGeneric TypesRecap - Shape Calculator5Inheritance
SubclassesOverriding MethodsInitializers and superfinal and HierarchiesRecap - Employee Hierarchy11Project: Library Management
Books and MembersBorrowing BooksPractice on your own: Swift playground