Hi everyone ;-)
Let's say I have an enum
enum MyEnum {
case one, two
}
I would like to create a function in my enum that returns a dynamic type depending on the value of the enum like this
extension MyEnum {
var myObject: T {
switch self {
case .one: return ObjectOne()
case .two: return ObjectTwo()
}
}
}
But (there's always a But...), I don't want to cast the receiver like
let _: ObjectOne = MyEnum.one.myObject
or
let _: MyEnum<ObjectOne> = .one.myObject
The kind of behavior that I would really like would be a dynamic typealias (this does not work of course)
extension MyEnum {
typealias T = {
switch self {
case .one: return ObjectOne.self
case .two: return ObjectTwo.self
}
} ()
}
// that would allow me to write this and _ would be of type ObjectOne
let _ = MyEnum.one.myObject
I tried protocols with associated types and static objects instead of enums, I tried nested protocol inside enums, I can't find a way to make it work
Any idea, or is this just no achievable ? Thanks 🙏
Yes, I understand. I've run into similar situations before, and I think the short answer is that an enum probably isn't going to be the best solution. Enums are normally great because they're convenient to use, but the fact that the "conceal" type information, at compile time at least, makes them too simplistic for a use-case like this.
Given your 3 video types (YoutubeVideo
etc), maybe a better solution would be to make a generic VideoManager
concrete type (not a protocol) whose generic parameter is a type conforming to Video
protocol. Then your factory function could look something like this:
struct VideoFactory {
func videoManager<T>(for videoType: T.Type) -> VideoManager<T> where T: Video {}
}
let youtubeVideoManager = .factory.videoManager(for: YoutubeVideo.self)