-
Notifications
You must be signed in to change notification settings - Fork 3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Improve key implementation #28
Conversation
We can add a assert in the setter to check is there anything wrong. var string: String? {
get {
objc_getAssociatedObject(
self,
Self.__associated_stringKey
) as? String?
?? nil
}
set {
objc_setAssociatedObject(
self,
Self.__associated_stringKey,
newValue,
.OBJC_ASSOCIATION_ASSIGN
)
assert(string == newValue) // <-- Add this.
}
}
static var __associated_stringKey: UnsafeRawPointer {
unsafeBitCast(
NSSelectorFromString("__macro_local_6stringfMu_"),
to: UnsafeRawPointer.self
)
} |
I think it is a good idea. |
Maybe this. set {
objc_setAssociatedObject(
self,
Self.__associated_stringKey,
newValue,
.OBJC_ASSOCIATION_ASSIGN
)
if type.of(string).confirm(to: Equitable.self) {
assert(string == newValue)
}
} |
@mlch911 This function may exist only in NSObject. |
I have made some changes to the way keys are generated in order to support future platforms, such as Linux, where the Objective-C runtime is not available. Instead of using Selector, function pointers are used as keys. static var __associated_boolKey: UnsafeRawPointer {
let f: @convention(c) () -> Void = {}
return unsafeBitCast(f, to: UnsafeRawPointer.self)
} |
Would this return the same pointer every time? Shouldn't this be like this? static let __associated_boolKey: UnsafeRawPointer = {
let f: @convention(c) () -> Void = {}
return unsafeBitCast(f, to: UnsafeRawPointer.self)
}() |
Closure functions are not defined dynamically, but statically, just like any other function definition. And for cases where it is not possible to define a property of a stored type, such as a protocol extension, I want to define it as a calculated type property as much as possible. |
Within a Protocol Extension, stored property could not be defined, and an error occurred in the definition of the AssociatedObject's Key.
Therefore, I modified the implementation of Key to use Selector.
related to: #24