Delegate.swift 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  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>: @unchecked Sendable {
  70. public init() {}
  71. private let propertyQueue = DispatchQueue(label: "com.onevcat.Kingfisher.DelegateQueue")
  72. private var _block: ((Input) -> Output?)?
  73. private var block: ((Input) -> Output?)? {
  74. get { propertyQueue.sync { _block } }
  75. set { propertyQueue.sync { _block = newValue } }
  76. }
  77. private var _asyncBlock: ((Input) async -> Output?)?
  78. private var asyncBlock: ((Input) async -> Output?)? {
  79. get { propertyQueue.sync { _asyncBlock } }
  80. set { propertyQueue.sync { _asyncBlock = newValue } }
  81. }
  82. public func delegate<T: AnyObject>(on target: T, block: ((T, Input) -> Output)?) {
  83. self.block = { [weak target] input in
  84. guard let target = target else { return nil }
  85. return block?(target, input)
  86. }
  87. }
  88. public func delegate<T: AnyObject>(on target: T, block: ((T, Input) async -> Output)?) {
  89. self.asyncBlock = { [weak target] input in
  90. guard let target = target else { return nil }
  91. return await block?(target, input)
  92. }
  93. }
  94. public func call(_ input: Input) -> Output? {
  95. return block?(input)
  96. }
  97. public func callAsFunction(_ input: Input) -> Output? {
  98. return call(input)
  99. }
  100. public func callAsync(_ input: Input) async -> Output? {
  101. return await asyncBlock?(input)
  102. }
  103. public var isSet: Bool {
  104. block != nil || asyncBlock != nil
  105. }
  106. }
  107. extension Delegate where Input == Void {
  108. public func call() -> Output? {
  109. return call(())
  110. }
  111. public func callAsFunction() -> Output? {
  112. return call()
  113. }
  114. }
  115. extension Delegate where Input == Void, Output: OptionalProtocol {
  116. public func call() -> Output {
  117. return call(())
  118. }
  119. public func callAsFunction() -> Output {
  120. return call()
  121. }
  122. }
  123. extension Delegate where Output: OptionalProtocol {
  124. public func call(_ input: Input) -> Output {
  125. if let result = block?(input) {
  126. return result
  127. } else {
  128. return Output._createNil
  129. }
  130. }
  131. public func callAsFunction(_ input: Input) -> Output {
  132. return call(input)
  133. }
  134. }
  135. public protocol OptionalProtocol {
  136. static var _createNil: Self { get }
  137. }
  138. extension Optional : OptionalProtocol {
  139. public static var _createNil: Optional<Wrapped> {
  140. return nil
  141. }
  142. }