I recently noticed a pretty nice mechanism which may come in handy in some situations ;)
Let’s imagine we have a Team
structure that needs a configuration in order to be initialized. If we want to get some information about the team, we will simply call team.info()
.
But at some point it turns out, that we would like to create another team object, however its configuratin is unknown. We probably shouldn’t initialize it with an empty array of players (let team = Team(configuration: [])
) as this could be reserved for a team without any players at all. What can we do about it?
As we already have an initializer that we use in many different places which we don’t want to change, we can use a protocol called ExpressibleByArrayLiteral
. This will allow us to create an enum like:
Now we can replace the constructor of a Team
object with
init(configuration: Configuration)
and use it this way:
let unknownTeam = Team(configuration: .unknown)
. Keep in mind, that we do not need to change the code that created the old team
let myTeam = Team(configuration: ["Foo", "Bar"])
, because an array will be translated to our enum as case players([Player])
.
If you find this interesting, then take a look at the official docs or ExpressibleByStringLiteral
, ExpressibleByNilLiteral
, ExpressibleByBooleanLiteral
, ExpressibleByFloatLiteral
and other ExpressibleBy*Literal
protocols ;)