Delegates: Difference between revisions

Content deleted Content added
added swift
Line 1,575: Line 1,575:


=={{header|Swift}}==
=={{header|Swift}}==
Allowing the delegate to be any type and taking advantage of dynamism of method lookup:
<lang swift>import Foundation
<lang swift>import Foundation


Line 1,584: Line 1,585:
weak var delegate: AnyObject?
weak var delegate: AnyObject?
func operation() -> String {
func operation() -> String {
if let v = self.delegate?.thing?() {
if let f = self.delegate?.thing {
return v
return f()
} else {
} else {
return "default implementation"
return "default implementation"
Line 1,605: Line 1,606:


// With a delegate that implements "thing":
// 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()
let d = Delegate()
a.delegate = d
a.delegate = d