4

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?

1
  • 3
    Hardly simpler, but this is the best I could do: var isReachable: Bool = { if case .reachable = status { return true }; return false }() Commented Nov 15, 2016 at 22:50

2 Answers 2

2

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
}
Sign up to request clarification or add additional context in comments.

Comments

0

(Since your full example doesn't do anything) If your motivation for this question is that you only want to perform some operation when the listener is called with "reachable" (similar to a completion being called with success: Bool), you can write:

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

If you wouldn't be satisfied with the readability—Yoda condition anyone?—you could combine it with kkoltzau's answer, which would allow you to write:

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

1 Comment

this was only an example, the full implementation looks different. I was just trying to ask a swift 3 related question about enums with associated values and equality.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.