I'm trying to do something like this:
typealias HumanId = Int
typealias RobotId = Int
func getHuman(at index: HumanId) -> Human
func getRobot(at index: RobotId) -> Robot
but as it is now I can call getHuman with RobotId just fine: getHuman(at: RobotId(0)).
How do I make this typesafe?
I understand that I can do something like:
struct HumanId { let id: Int }
struct RobotId { let id: Int }
...and some extra things to make these structs function as indices, but that would lead to some code duplication, and since I'm having more than 2 of these id-types I would like to shorten this somehow, with typealiases and generics perhaps in order to make them unique?
You could leverage Swift generics to achieve your goal. Introduce a generic
Indextype like this:and then use it like this:
Literal Indices
You could even use the
ExpressibleByIntegerLiteralprotocol to provide some syntax sugar when using literal indices:For instance:
But the following code will not build, so the solution is still typesafe-ish:
Comparable Indices
As suggested in the comments, we could also add
Comparableconformance as well (e.g., so you can use theIndexstruct as the index in a type conforming to the standardCollectionprotocol):Example: