Programming in Swift: Functions & Types

Jan 4 2022 Swift 5.5, iOS 15, Xcode 13

Part 4: Properties & Methods

33. Methods

Lesson Complete

Play Next Lesson
Next
Save for later
About this episode
See versions

See course reviews

See forum comments
Cinema mode Mark as Complete Download course materials
Previous episode: 32. Challenge: Properties Next episode: 34. Challenge: Methods

Update Notes: This course was originally recorded in 2019. It has been reviewed and all content and materials updated as of October 2021.

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.

You’ve already learned how to write your own methods. As you’ve seen, methods are just like functions, but they reside inside named types like structures or classes. Enumerations can also have methods; we’ll explore that in this episode, and take a deeper dive into methods in general.

32 enum Weekday: CaseIterable {
case monday, tuesday, wednesday, thursday, friday, saturday, sunday
36 Weekday.allCases
37 var weekday: Weekday = .tuesday
35 func advance(by dayCount: UInt) {

}
36 let indexOfToday = Weekday.allCases.firstIndex(of: self)!
let indexOfAdvancedDay = indexOfToday + dayCount
Int(dayCount)
39 indexOfAdvancedDay % Weekday.allCases.count
39 Weekday.allCases[indexOfAdvancedDay % Weekday.allCases.count]
35 mutating func …
39 self = Weekday…
weekday.advance(by: 6)
struct Time {
  var day: Weekday
  var hour: UInt
}
var time = Time(day: .monday, hour: 0)
51 init(day: Weekday, hour: UInt = 0) {
    self.day = day
    self.hour = hour
  }
var time = Time(day: .monday)
56 mutating func advance(byHours hourCount: UInt) {
    
  }
hour + hourCount
(hour + hourCount).quotientAndRemainder
…quotientAndRemainder(dividingBy: 24)
let (dayCount, hour) = (self.hour…
58 day.advance(by: dayCount)
    self.hour = hour
var time = Time(day: .monday)
😺time.advance(byHours: 24 * 3 + 5)🛑
62 func advanced(byHours hourCount: UInt) {

}
…) -> Time {
63 var time = self
63 time.advance(byHours: hourCount)
65 return time
67 😺let🛑 time = Time(day: .monday)
😺var advancedTime = time.advanced🛑(byHours: 24 * 3 + 5)
func advanced(byHours hourCount: UInt) -> Time {
  😺let (dayCount, hour) = (self.hour + hourCount).quotientAndRemainder(dividingBy: 24)🛑
let (dayCount, hour) = (self.hour + hourCount).quotientAndRemainder(dividingBy: 24)

😺var time = self
time.day.advance(by: dayCount)
time.hour = hour
return time🛑
56 mutating func advance(byHours hourCount: UInt) {
    self = self.advanced(byHours: hourCount)
  }
71 advancedTime.advance(byHours: 6)
struct Mathematics {
  static func getLength(x: Double, y: Double) -> Double {
  
  }
}
75 return (x * x + y * y).squareRoot()
Mathematics.getLength(x: 3, y: 4)
80 let mathematics = Mathematics()
73 enum Mathematics {