I have a large number of protocol compliant types which I am processing using an array, something like this:
protocol Thing {
func multiply(_ n: Int) -> Int
}
struct One: Thing {
func multiply(_ n: Int) -> Int { n * 1 }
}
struct Two: Thing {
func multiply(_ n: Int) -> Int { n * 2 }
}
var thingArray: [Thing] = []
let name = "Two"
switch name {
case "One":
thingArray.append(One())
case "Two":
thingArray.append(Two())
...
default:
()
}
This code works fine, but the problem is that there will ultimately be a large number of compliant types so the switch block will become large.
My question is this: Is there a way in Swift of assigning the protocol based on the value of a variable? something like this:
thingArray.append(Struct(name)())
It would be nice to replace the entires switch block with a single line.