From de6dc2e5b0d09d8f443df52febc9b8b47b4c3502 Mon Sep 17 00:00:00 2001 From: Gary Gan Date: Fri, 31 Jan 2025 09:27:46 +0800 Subject: [PATCH] finish protocols --- Protocols.playground/Contents.swift | 115 ++++++++++++++++++ Protocols.playground/contents.xcplayground | 2 + .../contents.xcworkspacedata | 3 + 3 files changed, 120 insertions(+) create mode 100644 Protocols.playground/Contents.swift create mode 100644 Protocols.playground/contents.xcplayground diff --git a/Protocols.playground/Contents.swift b/Protocols.playground/Contents.swift new file mode 100644 index 0000000..9da2941 --- /dev/null +++ b/Protocols.playground/Contents.swift @@ -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 + diff --git a/Protocols.playground/contents.xcplayground b/Protocols.playground/contents.xcplayground new file mode 100644 index 0000000..10de914 --- /dev/null +++ b/Protocols.playground/contents.xcplayground @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/swift-playground.xcworkspace/contents.xcworkspacedata b/swift-playground.xcworkspace/contents.xcworkspacedata index acdfada..90ecb82 100644 --- a/swift-playground.xcworkspace/contents.xcworkspacedata +++ b/swift-playground.xcworkspace/contents.xcworkspacedata @@ -1,6 +1,9 @@ + +