I'm playing with embedded swift, and I'm just curious, is what I'm trying to achieve somehow possible. I made protocol Multichannel, and struct Consumer, when one of variables has to have type dependent of struct content. Here is example code:
protocol Multichannel {
associatedtype Owner
}
//As T could be anything assigned to particular channel: some data, closure... whatever
struct OneChannel<T>: Multichannel {
typealias Owner = T
var value: T
}
struct Stereo<T>: Multichannel {
typealias Owner = T
var left: T
var right: T
}
struct RGB<T>: Multichannel {
typealias Owner = T
var red: T
var green: T
var blue: T
}
var monoNames = OneChannel(value: "Just One")
var stereoNames = Stereo(left: "left", right: "right")
var rgbNames = RGB(red: "red", green: "green", blue: "blue")
struct Consumer<M> where M: Multichannel {
enum Error: Swift.Error {
case bad
}
var handlers: any Multichannel
//var handlers: Current?M<Int> ??? ;)
init (names: M) throws (Error) where M.Owner == String {
switch names {
case is OneChannel<String> :
let names = names as! OneChannel<String>
self.handlers = OneChannel(value: names.value.count)
case is Stereo<String> :
let names = names as! Stereo<String>
self.handlers = Stereo(left: names.left.count,
right: names.right.count)
case is RGB<String> :
let names = names as! RGB<String>
self.handlers = RGB(red: names.red.count,
green: names.green.count,
blue: names.blue.count)
default: throw .bad
}
}
}
let test = try Consumer(names: monoNames)
print (test.handlers)
Because of any Multichannel embedded swift compiler shouts loudly. Is possible to somehow push those limits? Or avoid this kind of thinking?
FYI, Embedded Swift does support existentials of class-bound protocols, so if you don't mind making the protocol constrained to AnyObject and the instances be classes instead of structs, then any Multichannel should work fine. (Of course this is still a pretty big change to the data structures, and might not be desirable.)
That said, I think the type switch in Consumer.init() looks like something that I would avoid in any case (it's tight coupling of "independent" data structures), regardless of this being Embedded Swift or regular Swift.
So many people around here know so much more than I do that I fell into the curse of knowledge trap hereâassuming you had some motivation for not using that solution. Hopefully you're having more success this week!
Is set of channel combinations closed? Are these 3 the only ones possible?
I suspect enum might fit your needs better than a protocol:
enum Multichannel<T> {
case one(OneChannel<T>)
case stereo(Stereo<T>)
case rgb(Stereo<T>)
}
struct OneChannel<T> {
var value: T
}
struct Stereo<T> {
var left: T
var right: T
}
struct RGB<T> {
var red: T
var green: T
var blue: T
}