Last active
April 15, 2020 20:07
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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