Delegate.swift 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. //
  2. // Delegate.swift
  3. // Kingfisher
  4. //
  5. // Created by onevcat on 2018/10/10.
  6. //
  7. // Copyright (c) 2019 Wei Wang <onevcat@gmail.com>
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining a copy
  10. // of this software and associated documentation files (the "Software"), to deal
  11. // in the Software without restriction, including without limitation the rights
  12. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. // copies of the Software, and to permit persons to whom the Software is
  14. // furnished to do so, subject to the following conditions:
  15. //
  16. // The above copyright notice and this permission notice shall be included in
  17. // all copies or substantial portions of the Software.
  18. //
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. // THE SOFTWARE.
  26. import Foundation
  27. /// A class that maintains a weak reference to `self` when implementing `onXXX` behaviors.
  28. /// Instead of manually ensuring that `self` is kept as weak in a stored closure:
  29. ///
  30. /// ```swift
  31. /// // MyClass.swift
  32. /// var onDone: (() -> Void)?
  33. /// func done() {
  34. /// onDone?()
  35. /// }
  36. ///
  37. /// // ViewController.swift
  38. /// var obj: MyClass?
  39. ///
  40. /// func doSomething() {
  41. /// obj = MyClass()
  42. /// obj!.onDone = { [weak self] in
  43. /// self?.reportDone()
  44. /// }
  45. /// }
  46. /// ```
  47. ///
  48. /// You can create a `Delegate` and observe it on `self`. This ensures there is no retain cycle:
  49. ///
  50. /// ```swift
  51. /// // MyClass.swift
  52. /// let onDone = Delegate<(), Void>()
  53. /// func done() {
  54. /// onDone.call()
  55. /// }
  56. ///
  57. /// // ViewController.swift
  58. /// var obj: MyClass?
  59. ///
  60. /// func doSomething() {
  61. /// obj = MyClass()
  62. /// obj!.onDone.delegate(on: self) { (self, _) in
  63. /// // The `self` here is shadowed and does not retain a strong reference.
  64. /// // Thus, both the `MyClass` instance and the `ViewController` instance can be released.
  65. /// self.reportDone()
  66. /// }
  67. /// }
  68. ///
  69. public class Delegate<Input, Output> {
  70. public init() {}
  71. private var block: ((Input) -> Output?)?
  72. private var asyncBlock: ((Input) async -> Output?)?
  73. public func delegate<T: AnyObject>(on target: T, block: ((T, Input) -> Output)?) {
  74. self.block = { [weak target] input in
  75. guard let target = target else { return nil }
  76. return block?(target, input)
  77. }
  78. }
  79. public func delegate<T: AnyObject>(on target: T, block: ((T, Input) async -> Output)?) {
  80. self.asyncBlock = { [weak target] input in
  81. guard let target = target else { return nil }
  82. return await block?(target, input)
  83. }
  84. }
  85. public func call(_ input: Input) -> Output? {
  86. return block?(input)
  87. }
  88. public func callAsFunction(_ input: Input) -> Output? {
  89. return call(input)
  90. }
  91. public func callAsync(_ input: Input) async -> Output? {
  92. return await asyncBlock?(input)
  93. }
  94. }
  95. extension Delegate where Input == Void {
  96. public func call() -> Output? {
  97. return call(())
  98. }
  99. public func callAsFunction() -> Output? {
  100. return call()
  101. }
  102. }
  103. extension Delegate where Input == Void, Output: OptionalProtocol {
  104. public func call() -> Output {
  105. return call(())
  106. }
  107. public func callAsFunction() -> Output {
  108. return call()
  109. }
  110. }
  111. extension Delegate where Output: OptionalProtocol {
  112. public func call(_ input: Input) -> Output {
  113. if let result = block?(input) {
  114. return result
  115. } else {
  116. return Output._createNil
  117. }
  118. }
  119. public func callAsFunction(_ input: Input) -> Output {
  120. return call(input)
  121. }
  122. }
  123. public protocol OptionalProtocol {
  124. static var _createNil: Self { get }
  125. }
  126. extension Optional : OptionalProtocol {
  127. public static var _createNil: Optional<Wrapped> {
  128. return nil
  129. }
  130. }