In the Apple [iOS App Dev Tutorial] (as of Jan 22)(https://developer.apple.com/tutorials/app-dev-training), under the Creating a Navigation Hierarchy section, we extend a struct that we have defined.
I have tried reading the Swift documentation about extensions, but don't really understand why this is done here. The documentation talks about extending system types such as adding extra properties to the system type Double, but not adding extra properties to something that we have full control over, such as our own structure.
I am sure it is a best practice, as this is an Apple tutorial, but they don't really do a good job of explaining it.
This is an example of the code they want you to write:
import SwiftUI
struct DailyScrum: Identifiable {
let id: UUID
var title: String
var attendees: [Attendee]
var lengthInMinutes: Int
var theme: Theme
init(id: UUID = UUID(), title: String, attendees: [String], lengthInMinutes: Int, theme: Theme) {
self.id = id
self.title = title
self.attendees = attendees.map { Attendee(name: $0) }
self.lengthInMinutes = lengthInMinutes
self.theme = theme
}
}
extension DailyScrum {
struct Attendee: Identifiable {
let id: UUID
var name: String
init(id: UUID = UUID(), name: String) {
self.id = id
self.name = name
}
}
}
I am uncertain why the Attendee structure has to be defined within an extension. For example, this works too:
import SwiftUI
struct Attendee: Identifiable {
let id: UUID
var name: String
init(id: UUID = UUID(), name: String) {
self.id = id
self.name = name
}
}
struct DailyScrum: Identifiable {
let id: UUID
var title: String
var attendees: [Attendee]
var lengthInMinutes: Int
var theme: Theme
init(id: UUID = UUID(), title: String, attendees: [String], lengthInMinutes: Int, theme: Theme) {
self.id = id
self.title = title
self.attendees = attendees.map { Attendee(name: $0) }
self.lengthInMinutes = lengthInMinutes
self.theme = theme
}
}
I'm just not sure why you would do one over the other.