Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save phatblat/18b00cce256b0ebac0da to your computer and use it in GitHub Desktop.
Save phatblat/18b00cce256b0ebac0da to your computer and use it in GitHub Desktop.
Example of using Objective-C associated objects as the backing store for properties added via a Swift extension.
private var stringPropertyAssociationKey: UInt8 = 0
private var intPropertyAssociationKey: UInt8 = 0
// This is a replacement for a custom UICollectionViewLayoutAttributes subclass since
// layoutAttributesForElementsInRect() is crashing when a subclass is registered.
// https://devforums.apple.com/message/1120429#1120429
//
// http://stackoverflow.com/questions/25426780/swift-extension-stored-properties-alternative#answer-25428013
// http://stackoverflow.com/questions/24133058/is-there-a-way-to-set-associated-objects-in-swift#answer-25428409
extension UICollectionViewLayoutAttributes {
var stringProperty: String {
get {
let optionalObject: AnyObject? = objc_getAssociatedObject(self, &stringPropertyAssociationKey)
if let object: AnyObject = optionalObject {
return object as! String
}
return ""
}
set(newValue) {
objc_setAssociatedObject(self, &stringPropertyAssociationKey, newValue, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN))
}
}
var intProperty: Int {
get {
let optionalObject: AnyObject? = objc_getAssociatedObject(self, &intPropertyAssociationKey)
if let object: AnyObject = optionalObject {
return object as! Int
}
return 0
}
set(newValue) {
objc_setAssociatedObject(self, &intPropertyAssociationKey, newValue, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment