Skip to content

Instantly share code, notes, and snippets.

@baarde
Created January 20, 2016 11:29
Show Gist options
  • Save baarde/78598cd98c830497123c to your computer and use it in GitHub Desktop.
Save baarde/78598cd98c830497123c to your computer and use it in GitHub Desktop.
Mixing methods and properties in Swift
protocol Worker {
func work()
}
struct AnyWorker: Worker {
let work: () -> Void
func work() {
print("1")
work()
}
}
let worker: Worker = AnyWorker {
print("2")
}
worker.work()
// Does not compile:
// Invalid redeclaration of 'work()'
protocol Worker {
func work(task: Any)
}
struct AnyWorker: Worker {
let work: Any -> Void
func work(task: Any) {
print("1")
work(task)
}
}
let worker: Worker = AnyWorker { task in
print("2")
}
worker.work(Void())
// Prints:
// 1
// 2
protocol Worker {
func work(task: Any)
}
struct AnyWorker: Worker {
let work: (task: Any) -> Void
func work(task: Any) {
print("1")
work(task)
}
}
let worker: Worker = AnyWorker { task in
print("2")
}
worker.work(Void())
// Prints:
// 1
// 1
// 1
// ...
// until task overflow
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment