finish protocols

This commit is contained in:
Gary Gan 2025-01-31 09:27:46 +08:00
parent 109bd67369
commit de6dc2e5b0
3 changed files with 120 additions and 0 deletions

View File

@ -0,0 +1,115 @@
import Foundation
protocol CanBreathe {
func breathe()
}
struct Animals: CanBreathe {
func breathe() {
"Animal Breathing..."
}
}
struct Person: CanBreathe {
func breathe() {
"Person breathing"
}
}
let dog = Animals()
dog.breathe()
let foo = Person()
foo.breathe()
protocol CanJump {
func jump()
}
extension CanJump {
func jump() {
"Jumping..."
}
}
struct Cat: CanJump {
func jump() {
"Cat can jump..."
}
}
let cat = Cat()
cat.jump()
protocol HasName {
var name: String { get }
var age: Int { get set }
}
extension HasName {
func describeMe() {
"Your name is \(name) and you are \(age) years old"
}
mutating func increaseAge() {
self.age += 1
}
}
struct Dog: HasName {
let name: String
var age: Int
}
var woof = Dog(name: "Woof", age: 10)
woof.name
woof.age
woof.increaseAge()
woof.age
woof.describeMe()
protocol Vehicle {
var speed: Int { get set }
mutating func increaseSpeed(by value: Int)
}
extension Vehicle {
mutating func increaseSpeed(by value: Int) {
self.speed += value
}
}
struct Bike: Vehicle {
var speed: Int = 0
}
var bike = Bike()
bike.speed
bike.increaseSpeed(by: 40)
bike.speed
func describe(obj: Any) {
if obj is Vehicle {
"Yes"
} else {
"No"
}
}
describe(obj: bike)
func increaseSpeedIfVehicle(obj: Any) {
if var vechile = obj as? Vehicle {
vechile.speed
vechile.increaseSpeed(by: 10)
vechile.speed
} else {
"something else"
}
}
increaseSpeedIfVehicle(obj: bike)
bike.speed // 40 struct is a copy type

View File

@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<playground version='7.0' target-platform='macos' swift-version='6' buildActiveScheme='true' executeOnSourceChanges='true' importAppTypes='true'/>

View File

@ -1,6 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "group:Protocols.playground">
</FileRef>
<FileRef
location = "group:Classes.playground">
</FileRef>