Delegates: Difference between revisions

(added swift)
Line 1,575:
 
=={{header|Swift}}==
Allowing the delegate to be any type and taking advantage of dynamism of method lookup:
<lang swift>import Foundation
 
Line 1,584 ⟶ 1,585:
weak var delegate: AnyObject?
func operation() -> String {
if let vf = self.delegate?.thing?() {
return vf()
} else {
return "default implementation"
Line 1,605 ⟶ 1,606:
 
// With a delegate that implements "thing":
let d = Delegate()
a.delegate = d
println(a.operation()) // prints "delegate implementation"</lang>
 
 
Alternately, requiring the delegate to conform to a given protocol:
<lang swift>protocol Thingable : class {
func thing() -> String
}
 
class Delegator {
weak var delegate: Thingable?
func operation() -> String {
if let d = self.delegate {
return d.thing()
} else {
return "default implementation"
}
}
}
 
class Delegate : Thingable {
func thing() -> String { return "delegate implementation" }
}
 
// Without a delegate:
let a = Delegator()
println(a.operation()) // prints "default implementation"
 
// With a delegate:
let d = Delegate()
a.delegate = d
Anonymous user