Skip to content

Instantly share code, notes, and snippets.

@biloshkurskyi-ss
Last active July 30, 2019 11:12
Show Gist options
  • Save biloshkurskyi-ss/511709845f8523c0bb1d423f9af3b2d2 to your computer and use it in GitHub Desktop.
Save biloshkurskyi-ss/511709845f8523c0bb1d423f9af3b2d2 to your computer and use it in GitHub Desktop.
OOP at Swift - Polymorphism
import Foundation
class Vehicle {
var model: String
var make: Int
init(model: String, make: Int) {
self.model = model
self.make = make
}
func start() { print("Vehicle - Start") }
func stop() { print("Vehicle - Stop") }
}
class Car: Vehicle {
var tireCount: Int
private var isEngineWorks = false {
didSet {
print("Engine working: \(isEngineWorks)")
}
}
init(model: String, make: Int, tireCount: Int = 4) {
self.tireCount = tireCount
super.init(model: model, make: make)
}
override func start() {
startEngine()
print("Car - Start")
}
override func stop() {
super.stop()
stopEngine()
}
private func startEngine() {
isEngineWorks = true
}
private func stopEngine() {
isEngineWorks = false
}
}
class Bike: Vehicle {
func getInforation() -> String {
return "Bike model: \(model) maked: \(make)"
}
}
let сuriosity = Vehicle(model: "Rover", make: 2011)
let bike = Bike(model: "Pinarello", make: 2019)
let ford = Car(model: "Ford", make: 2018)
let vechicles = [сuriosity, bike, ford]
vechicles.forEach { vechicle in
print("Class: \(String(describing: vechicle)) model: \(vechicle.model)")
vechicle.start()
vechicle.stop()
print("\n")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment