Learn SwiftUI (Day 13/100)
BC
Posted on May 2, 2024
Swift
- protocols
- extensions
- protocol extensions
import Cocoa
// ## protocol
// {get set} -> no comman in between
// {get} or {get set}, not possible for just {set}
protocol Vehicle {
var name: String { get }
var currentPassengers: Int { get set }
func estimateTime(for distance: Int) -> Int
func travel(distance: Int)
}
struct Rocket: Vehicle {
let name = "rocket"
var currentPassengers = 0
func estimateTime(for distance: Int) -> Int {
return distance / 100
}
func travel(distance: Int) {
print("\(name) traveled \(distance) already")
}
}
var r = Rocket()
r.travel(distance: 12)
// opaque return type
/*
they let us hide information in our code, but not from the Swift compiler.
This means we reserve the right to make our code flexible
internally so that we can return different things in the future,
but Swift always understands the actual data type being returned
and will check it appropriately.
*/
func getRandomNumber() -> some Equatable {
Int.random(in: 1...6)
}
/*
when you see some View in your SwiftUI code, it’s effectively us telling
Swift “this is going to send back some kind of view to lay out, but I don’t
want to write out the exact thing – you figure it out for yourself.”
*/
// ## Extentions
/*
Extensions let us add functionality to any type, whether we created it or
someone else created it – even one of Apple’s own types.
*/
extension String {
func trimmed() -> String {
self.trimmingCharacters(in: .whitespacesAndNewlines)
}
}
let a = " hello world "
print(a.trimmed())
/*
If want to change the string itself, use:
mutating func trim() {
self = self.trimmed()
}
*/
// ## can add computed property extension to a type
/*
var lines: [String] {
self.components(separatedBy: .newlines)
}
*/
// ## put custom init in extension
/*
if we implement a custom initializer inside an extension, then Swift won’t
disable the automatic memberwise initializer.
extension Book {
init(title: String, pageCount: Int) {
self.title = title
self.pageCount = pageCount
self.readingHours = pageCount / 50
}
}
*/
// ## protocol extensions
extension Collection {
var isNotEmpty: Bool {
isEmpty == false
}
}
// use extension to implement a default method in protocol
protocol Person {
var name: String { get }
func sayHello()
}
extension Person {
func sayHello() {
print("Hi, I'm \(name)")
}
}
💖 💪 🙅 🚩
BC
Posted on May 2, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.