CocoaPods trunk is moving to be read-only. Read more on the blog, there are 19 months to go.

HasAssociatedObjects 2.0.0

HasAssociatedObjects 2.0.0

TestsTested
LangLanguage SwiftSwift
License MIT
ReleasedLast Release Oct 2017
SwiftSwift Version 3.0
SPMSupports SPM

Maintained by tokorom.



  • By
  • tokorom

HasAssociatedObjects

==================




We can add some stored objects to Swift extension

Q. Can we add a stored property to extension?

A. No, but we can use assciated objects instead.

Simple Usage

extension UIViewController: HasAssociatedObjects {

    // new stored property
    var storedString: String? {
        get {
            return associatedObjects.value as? String
        }
        set {
            associatedObjects.value = newValue
        }
    }

}

Other Usages

Multiple stored properties

extension UIViewController: HasAssociatedObjects {

    var storedString: String? {
        get {
            return associatedObjects["STRING"] as? String
        }
        set {
            associatedObjects["STRING"] = newValue ?? ""
        }
    }

    var storedInt: Int {
        get {
            guard let value = associatedObjects["INT"] as? Int else {
                return 0 //< default value
            }
            return value
        }
        set {
            associatedObjects["INT"] = newValue
        }
    }

}

Use directly

extension Subject: HasAssociatedObjects {
}

subject.associatedObjects.value = 10

let storedValue = subject.associatedObjects.value as? Int
XCTAssertEqual(10, storedValue)

Subject is not AnyObject

// subject is struct
struct AnySubject {
    let identifier: Int
}

// a appropriate property that can be cleaned
var propertyOfSomeone: [Int: AssociatedObjects] = [:]

// You can customize `associatedObjects`
extension AnySubject: HasAssociatedObjects {
    var associatedObjects: AssociatedObjects {
        guard let associatedObjects = propertyOfSomeone[hashValue] else {
            let associatedObjects = AssociatedObjects()
            propertyOfSomeone[hashValue] = associatedObjects
            return associatedObjects
        }
        return associatedObjects
    }
}

extension AnySubject: Hashable {
    var hashValue: Int {
        return identifier
    }

    static func == (lhs: AnySubject, rhs: AnySubject) -> Bool {
        return lhs.hashValue == rhs.hashValue
    }
}

Installation