Skip to content

Instantly share code, notes, and snippets.

@dabear
Last active January 19, 2020 11:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dabear/6a5d720e9c683bd7a30c5c915fdcc733 to your computer and use it in GitHub Desktop.
Save dabear/6a5d720e9c683bd7a30c5c915fdcc733 to your computer and use it in GitHub Desktop.
@dynamicMemberLookup
class QueuedPropertyAccess<U:AnyObject>{
weak var anObj : U?
weak var dispatchQueue: DispatchQueue!
init(_ anObj:U, dispatchQueue:DispatchQueue) {
self.anObj = anObj
self.dispatchQueue = dispatchQueue
}
subscript<T>(dynamicMember keyPath: KeyPath<U, T>) -> T {
//We need to store an Optional<Optional<T>> (nested optional) here
//unwrapping this is ok as long as the dispatchqueue assigns a result to the variable
var result: T? = nil
dispatchQueue.sync {
result = self.anObj?[keyPath: keyPath]
}
//result = self.anObj?[keyPath: keyPath]
if (result as? Self) === self {
fatalError("self reference not allowed")
}
return result!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment