Last active
December 5, 2018 12:43
-
-
Save sorin-ref/4971a2e771308e3f02c2e4896fc0b232 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 3. Service that requests input and output from a client as @escaping or optional closures (i.e. the functional approach). No more inheritance, and the service can still provide default implementations whenever needed. But the clients need to capture weak/unowned self if they want to use their current state within the body of the custom closures passed to the service (in order to avoid memory leaks, i.e. they need to know how ARC works). | |
public class Service3 { | |
public init(inputFunction: @escaping InputFunction, outputFunction: OutputFunction? = nil) { | |
self.inputFunction = inputFunction | |
self.outputFunction = outputFunction | |
} | |
private var inputFunction: InputFunction | |
private var outputFunction: OutputFunction? | |
public func doSomething() { | |
if inputFunction() { | |
let text = "done" | |
if let outputFunction = outputFunction { | |
outputFunction(text) | |
} else { | |
print(type(of: self), text) | |
} | |
} | |
} | |
} | |
public typealias InputFunction = () -> Bool | |
public typealias OutputFunction = (String) -> Void | |
class Client3 { | |
var input = true | |
func doSomething() { | |
let service3 = Service3( | |
inputFunction: { [unowned self] in | |
return self.input | |
}) | |
service3.doSomething() | |
} | |
} | |
Client3().doSomething() // prints "Service3 done" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment