Downsides to making a common type like URL conform to Identifiable?

SwiftUI uses Identifiable a lot. In one case I want to pass a URL to sheet(item:content:) so it needs to be Identifiable. I wrote this...

extension URL: Identifiable {
    public var id: URL { self }
}

It gives me an uneasy feeling, like a global variable. But I'm not sure what problems it could cause. Opinions welcome. :)

An alternative is something like:

struct SheetInfo: Identifiable {
    let id: UUID = .init()
    let url: URL
}

i had exactly that feeling when making String identifiable...

in your own projects or your team's projects where all are aware of this feature, it'll probably be ok. the problems could arise in bigger projects with different components done by different people or when using third party frameworks - different components might disagree on what identity of URL shall be. so for starters there could be "already defined" compilation errors. then there could be more subtle cases when a different component wants to treat some url's "identical" (having the same identity) even when they are not equal:

https://host/path?hello=1&world=2
https://host/path?world=2&hello=1

all in all, as a rule i wouldn't recommend it, but you may get away with it in many apps with no problem.

as an alternative you may do just that:

struct IdentifiableURL: Identifiable {
    public var id: URL
}

i.e. no need to reach out for UUID in this case.

1 Like

This is called a retroactive conformance and you can read the nuances here:

And yes, the airtight solution is to wrap it in another type like you have both demonstrated.

1 Like
Terms of Service

Privacy Policy

Cookie Policy