Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save 23inhouse/af9daf93828690527e883088bb917d53 to your computer and use it in GitHub Desktop.
Save 23inhouse/af9daf93828690527e883088bb917d53 to your computer and use it in GitHub Desktop.
ChatGPT3 response to "swift code exemplifying sandy metz style duck types"
[email protected]
swift code exemplifying sandy metz style duck types
Sure, here's an example of a Swift code that uses duck typing, in a style similar to that of Sandi Metz:
swift
Copy code
protocol Quackable {
func quack() -> String
}
class Duck: Quackable {
func quack() -> String {
return "Quack!"
}
}
class Person {
func quackLikeADuck(duck: Quackable) -> String {
return duck.quack()
}
}
let duck = Duck()
let person = Person()
person.quackLikeADuck(duck: duck) // Output: "Quack!"
In this example, we have two classes - Duck and Person. Duck implements the Quackable protocol, which has a single method quack() that returns a string. Person has a method quackLikeADuck() that takes a Quackable object as an argument and calls its quack() method.
The beauty of duck typing is that the Person class doesn't care whether the object it receives is actually a Duck or any other class that implements the Quackable protocol - as long as it quacks like a duck (i.e. has a quack() method that returns a string), it will work just fine. This allows for more flexible and reusable code, since the Person class can work with any object that quacks like a duck, regardless of its specific implementation.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment