Skip to content

Instantly share code, notes, and snippets.

@imjhk03
Created July 29, 2021 05:49
Show Gist options
  • Select an option

  • Save imjhk03/4e21d7ac8dc2ca8ae44394a2584006c5 to your computer and use it in GitHub Desktop.

Select an option

Save imjhk03/4e21d7ac8dc2ca8ae44394a2584006c5 to your computer and use it in GitHub Desktop.
Sample code about providing default value with protocol extensions
import UIKit
protocol Moveable {
func move(to point: CGPoint)
}
extension Moveable {
func move(to point: CGPoint = .zero) {
move(to: point)
}
}
protocol Talkable {
var greetings: String { get }
}
extension Talkable {
var greetings: String {
return "Hello"
}
}
struct Character: Moveable, Talkable {
let name: String
init(name: String) {
self.name = name
}
func move(to point: CGPoint) {
print("\(name) moved to \(point)")
}
}
let mario = Character(name: "Mario")
mario.move(to: CGPoint(x: 3, y: 0))
let luigi = Character(name: "Luigi")
luigi.move()
print(mario.greetings)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment