efremidze efremidze - 23 days ago 11
Swift Question

Compare Enum with Associated Value Short Syntax

I'm trying to simplify

var isReachable = {
switch status {
case .reachable: return true
default: return false
}
}()


to something like

var isReachable = (case status == .reachable)


Here is the full example:

enum NetworkReachabilityStatus {
case unknown
case notReachable
case reachable(Alamofire.NetworkReachabilityManager.ConnectionType)
}

NetworkReachabilityManager().listener = { status in
var isReachable = {
switch status {
case .reachable: return true
default: return false
}
}()
}


This is only an issue when you are dealing with enums with associated values. Any suggestions?

Answer

An extension on NetworkReachabilityStatus can make this work.

extension NetworkReachabilityStatus {
    var isReachable: Bool {
        switch self {
            case .reachable(_): return true
            default: return false
        }
    }
}

NetworkReachabilityManager().listener = { status in
    var isReachable = status.isReachable
}