How to make a dependency of a protocol #25
-
I'm trying to add a dependency that would use a protocol as a type. However, I'm not able to use private enum StylerKey: DependencyKey {
static let liveValue: some StylerProviding = StylerProvider()
}
extension DependencyValues {
var stylerProvider: some StylerProviding {
get { self[StylerKey.self] }
set { self[StylerKey.self] = newValue }
}
}
What's the best practise? I could try with private enum StylerKey: DependencyKey {
static let liveValue: any StylerProviding = StylerProvider()
}
extension DependencyValues {
var stylerProvider: any StylerProviding {
get { self[StylerKey.self] }
set { self[StylerKey.self] = newValue }
}
}
struct MyStruct {
@Dependency(\.stylerProvider) var styler
func test() {
MyGenericStruct(styler: styler) // This would of course complain that 'any StylerProviding' cannot conform to 'StylerProviding'
}
}
struct MyGenericStruct<S: StylerProviding> {
let styler: S
} Or is it in fact discouraged to use protocols with |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Hey @kakhaberikiknadze! If you want to use protocols, you should probably use existentials ( Another solution would be to redesign your dependency to not use protocols. See for example this section of the documentation, which is functionally equivalent to erasing your protocol. You can totally imagine having a generic init to this struct, to easily wrap your existing There are other solutions, but this is likely the road I would take. Can you tell us more about I'd also recommend to watch this WWDC session about |
Beta Was this translation helpful? Give feedback.
Hey @kakhaberikiknadze! If you want to use protocols, you should probably use existentials (
any
) all the way. The performance impact is something that is often mentioned, but it may be very marginal in your situation (if not all).Another solution would be to redesign your dependency to not use protocols. See for example this section of the documentation, which is functionally equivalent to erasing your protocol. You can totally imagine having a generic init to this struct, to easily wrap your existing
StyleProviding
types.There are other solutions, but this is likely the road I would take. Can you tell us more about
MyGenericStruct
generic requirement? DoesStylerProviding
have anassoc…