Protocols in Swift - Part 2
So having started learning about these, I know that I'm just scratching the surface. Last time, I got my head around some of the syntax - now it's about understanding the meaning of them in context. Here we go!
import Foundation
enum EmployeeType {
case manager
case traditional
}
struct Paycheck {
let base: Double
let benefits: Double
let deductions: Double
let vacation: String
}
class Employee {
let name: String
let address: String
let startDate: Date
let type: EmployeeType
init (name: String, address: String, startDate: Date, type: EmployeeType) {
self.name = name
self.address = address
self.startDate = startDate
self.type = type
}
}
class HourlyEmployee: Employee {
var hourlyWage = 15.00
var hoursWorked = 0
let vacation = 0
}
class SalariedEmployee: Employee {
var salary = 50000.00
var benefis = 1000.00
var deductions = 0.0
var vacation = 2
}
func pay(employee: Employee) {
employee.pay()
}
This is a very complex example! I think what Pasan is getting at is a protocol is going to be useful....Having so many classes means a mistake e.g. forget to override something could cause bugs in the program. If that bug went unnoticed then it could be problematic.
There's more code created, with a protocol, which allows any type in the future that conforms to the protocol. This means the function is more adaptable.
The rest of this has gone over my head...protocols are tricky!
The good thing about all of this is it's got me thinking about shaping elements of the F1 game and giving 'behaviours' to certain aspects of it. E.g. 'corner' or 'braking' can take a whole life of their own! Then they can be combined with other classes/protocols to create very precise code. I hadn't thought about having each aspect as a class but I'm starting to. But before the classes, a general outcome could be a protocol. Still not much clearer than mud but still good to know about. Next time we'll be moving onto protocol inheritance...
Comments
Post a Comment