kevinabraham kevinabraham - 6 months ago 13
Swift Question

How to create a closure to return which one of the parameters is true?

I need to create some sort of closure to return back if it's an optional or forced update. I've created some pseudo code:

func verifyAppVersionWithServer(isForceUpdate: bool -> true, isOptionalUpdate: bool -> true) {
//Some check will be performed here then:
if isForceUpdate {
return isForceUpdate -> true
} else {
return isOptionalUpdate -> true
}
}


I'm not sure how to create a closure in Swift which will then return which of the parameters is true.

Answer

It is probably nicer to return an enum that indicates the type of update required.

You would then have something like this:

enum UpdateType {
    case None
    case Optional
    case Required
}

func verifyAppVersionWithServer(completion:(UpdateType) -> Void) {

    let anyUpdate = true
    let forcedUpdate = false

    if anyUpdate {
        if forcedUpdate {
            completion(.Required)
        } else {
            completion(.Optional)
        }
    } else {
        completion(.None)
    }
}

You would call it as:

verifyAppVersionWithServer { (updateType) in
    print("Update type is \(updateType)")
}

Obviously the values would be determined by your server response, not fixed values as I have shown.