Created
September 2, 2023 19:33
-
-
Save zippi-MD/7079f981037e43d3cfb80cfbc147e649 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
// Extensions | |
extension Double { | |
var squared: Double { return self * self} | |
} | |
let sideLength: Double = 12.5 | |
let area = sideLength.squared | |
//print(area) | |
struct Car { | |
let maker: String | |
let model: String | |
let year: Int | |
var fuelLevel: Double { | |
willSet { | |
precondition(newValue <= 1.0 && newValue >= 0.0, "New value must be between 0 and 1") | |
} | |
} | |
} | |
// Conform protocol | |
extension Car: CustomStringConvertible { | |
var description: String { | |
"\(maker) - \(model)" | |
} | |
} | |
// Initializers | |
extension Car { | |
init(maker: String, model: String) { | |
self.init(maker: maker, | |
model: model, | |
year: 2023, | |
fuelLevel: 1.0) | |
} | |
} | |
// Nested type | |
extension Car { | |
enum Era { | |
case vintage, classic, modern | |
} | |
var era: Era { | |
switch year { | |
case ...1990: | |
return .vintage | |
case 1991...2000: | |
return .classic | |
case 2001...: | |
return .modern | |
default: | |
return .modern | |
} | |
} | |
} | |
// add method | |
extension Car { | |
mutating func fillFuel() { | |
fuelLevel = 1.0 | |
} | |
} | |
var firstCar = Car(maker: "Honda", | |
model: "Civic", | |
year: 2000, | |
fuelLevel: 0.5) | |
print(firstCar.fuelLevel) | |
firstCar.fillFuel() | |
print(firstCar.fuelLevel) | |
let secondCar = Car(maker: "Nissan", model: "Sentra") | |
print(firstCar.era) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment