This is related to "How do you forward opaque inputs to default implementation outputs without a derived protocol?" but this is a simpler question. (Use case for this, here.)
You have a protocol requirement that uses an associated type.
protocol Protocol {
associatedtype Property
var property: Property { get }
}
You want to use an opaque value to define Property.
var opaqueValue: some Any {
"This is from a 3rd party API and must be opaque."
}
It cannot be done directly.
struct Conformer: Protocol { // Type 'Conformer' does not conform to protocol 'Protocol'
init() { property = opaqueValue }
var property: Property // Reference to invalid associated type 'Property' of type 'Conformer'
}
But it can be done via another protocol. Is that really the simplest solution?
struct Conformer {
init() { property = Self._property() }
var property: Property
}
private protocol _Conformer: Protocol where Property == OpaqueProperty {
associatedtype OpaqueProperty
static func _property() -> OpaqueProperty
}
extension Conformer: _Conformer {
static func _property() -> some Any { opaqueValue }
}
Clarification: It must be possible to refer to the resulting type, such as for defining a variable of its type.
struct Requirement {
let requirement: Conformer
}