Compare Enum with the associated Short Syntax value

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 a complete 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 a problem when dealing with enumerations with related values. Any suggestions?

+4
source share
2 answers

Extending to NetworkReachabilityStatus can do the job.

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

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

(Since your complete example does nothing). If your motivation for this question is that you want to perform some operation only when the listener is called β€œreachable” (similar to the termination that is called with success: Bool), you can write:

NetworkReachabilityManager().listener = { status in
    if case .reachable(_) = status {
       // perform some operation
    }
}

- - ? - kkoltzau, :

NetworkReachabilityManager().listener = { status in
    if status.isReachable {
       // perform some operation
    }
}
0

Source: https://habr.com/ru/post/1660864/


All Articles