WrappedAssociatedObjects.swift 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. //
  2. // AssociatedObjects.swift
  3. // Kingfisher
  4. //
  5. // Created by João D. Moreira on 31/08/16.
  6. // Copyright © 2016 Wei Wang. All rights reserved.
  7. //
  8. import ObjectiveC
  9. /**
  10. * This file provides a wrapper around Objective-C runtime associated objects.
  11. * All values are wrapped in an instance of Wrapper allowing us to persist Swift value types.
  12. */
  13. private final class Wrapper<T> {
  14. let value: T
  15. init(_ x: T) {
  16. value = x
  17. }
  18. }
  19. private func wrap<T>(x: T) -> Wrapper<T> {
  20. return Wrapper(x)
  21. }
  22. func setAssociatedObject<T>(object: AnyObject, value: T, associativeKey: UnsafePointer<Void>, policy: objc_AssociationPolicy = .OBJC_ASSOCIATION_RETAIN_NONATOMIC) {
  23. if let v: AnyObject = value as? AnyObject {
  24. objc_setAssociatedObject(object, associativeKey, v, policy)
  25. } else {
  26. objc_setAssociatedObject(object, associativeKey, wrap(value), policy)
  27. }
  28. }
  29. func getAssociatedObject<T>(object: AnyObject, associativeKey: UnsafePointer<Void>) -> T? {
  30. let v = objc_getAssociatedObject(object, associativeKey)
  31. if let v = v as? T {
  32. return v
  33. } else if let v = v as? Wrapper<T> {
  34. return v.value
  35. } else {
  36. return nil
  37. }
  38. }