by dep_b · 8y ago · 0 comments
A Swift-enum allows you to have methods inside enums:
enum ConnectionStatus {
case connected
case connecting
case disconnecting
case disconnected
func `for`(isConnected: Bool, isConnecting: Bool, isDisconnecting: Bool) -> ConnectionStatus {
switch (isConnected, isConnecting, isDisconnecting) {
case (true, _, false): return .connected
case (false, true, _): return .connecting
case (true, _, false): return .disconnecting
case (false, false, _): return .disconnected
}
}
Then somewhere inside your code: public func connect() {
switch ConnectionStatus.for(isConnected: self.isConnected, isConnecting: self.isConnecting, isDisconnecting: self.isDisconnecting {
case .connected, .connecting: return // We're already good
case .disconnecting: reconnectWhenDisconnected()
case .disconnected: startConnection()
}
The amount of if's that have to be juggled to do the same and the resulting code that is hard to parse when you're maintaining it definitely is more problematic.