==================
We can add some stored objects to Swift extension
A. No, but we can use assciated objects instead.
extension UIViewController: HasAssociatedObjects {
// new stored property
var storedString: String? {
get {
return associatedObjects.value as? String
}
set {
associatedObjects.value = newValue
}
}
}
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
}
}
}
extension Subject: HasAssociatedObjects {
}
subject.associatedObjects.value = 10
let storedValue = subject.associatedObjects.value as? Int
XCTAssertEqual(10, storedValue)
// 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
}
}
CocoaPods is a dependency manager for Cocoa projects.
You can install it with the following command:
$ gem install cocoapods
To integrate HasAssociatedObjects into your Xcode project using CocoaPods, specify it in your Podfile
:
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!
pod 'HasAssociatedObjects'
Then, run the following command:
$ pod install
Carthage is a decentralized dependency manager that automates the process of adding frameworks to your Cocoa application.
You can install Carthage with Homebrew using the following command:
$ brew update
$ brew install carthage
To integrate HasAssociatedObjects into your Xcode project using Carthage, specify it in your Cartfile
:
github "tokorom/HasAssociatedObjects"
Then, run the following command:
$ carthage update
Then, link your app with HasAssociatedObjects.framework
.