IMO the purpose of an enum is to store data that varies by case (in type theoretical terms, it’s a sum type). In it’s simplest form this is just the cases of the enum.
enum State {
case opening
case connected
case closed
}
However, in a more complex case you can have associated values.
enum State {
case opening(connection: TCPConnection)
case connected(connection: TCPConnection, bytesSent: Int, bytesReceived: Int)
case closed
}
In this context the
connection
value makes no sense in the
.closed
state, and the
bytesSent
and
bytesReceived
values don’t make sense in the
.opening
state.
Now, imagine you have a value that makes sense in all states. You could model this like this:
enum State {
case opening(hostName: String, connection: TCPConnection)
case connected(hostName: String, connection: TCPConnection, bytesSent: Int, bytesReceived: Int)
case closed(hostName: String, bytesSent: Int, bytesReceived: Int)
}
but that’s kinda silly because
hostName
doesn’t vary by case and that’s exactly what associated values are for. It seems that you would like to model it like this:
enum State {
let hostName: String
case opening(connection: TCPConnection)
case connected(connection: TCPConnection, bytesSent: Int, bytesReceived: Int)
case closed(bytesSent: Int, bytesReceived: Int)
}
but, again, that runs counter to the concept of an enum, where the data is supposed to vary by the case. The correct way to model it is like this:
struct Connection {
let hostName: String
enum State {
case opening(connection: TCPConnection)
case connected(connection: TCPConnection, bytesSent: Int, bytesReceived: Int)
case closed(bytesSent: Int, bytesReceived: Int)
}
}
That is, use each construct for the purpose for which it was intended:
Share and Enjoy
—
Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
let myEmail = "eskimo" + "1" + "@apple.com"