0

I have to add a property to URLRequest for tracking purpose. I have tried using objc_setAssociatedObject like this:

public extension URLRequest {
    
    private struct AssociatedKeys {
        static var _trackingID = "_trackingID"
    }
    
    var trackingID: String? {
        get {
            return objc_getAssociatedObject(self, &AssociatedKeys.trackingID) as? String
        }
        set {
            if let newValue = newValue {
                objc_setAssociatedObject(
                    self,
                    &AssociatedKeys.trackingID,
                    newValue,
                    .OBJC_ASSOCIATION_RETAIN_NONATOMIC
                )
            }
        }
    }
    
}

But it seems not working for struct like URLRequest. Is there any way to add a stored property to struct extension?

1 Answers1

2

STATIC stored properties are permitted. You can add a private static dictionary in a URLRequest extension, use a URLRequest instance as a key, and the associated trackingID string as a value. Then, you can wrap it all up in public or internal methods for storing and fetching the values.

Arik Segal
  • 2,963
  • 2
  • 17
  • 29