swift - 如何创建一个闭包来返回哪个参数为 true?

标签 swift

如果是可选或强制更新,我需要创建某种关闭来返回。我创建了一些伪代码:

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

我不确定如何在 Swift 中创建一个闭包,然后返回哪个参数为 true。

最佳答案

返回一个指示所需更新类型的枚举可能会更好。

然后你会得到这样的东西:

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)
    }
}

您可以将其称为:

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

显然,这些值将由您的服务器响应决定,而不是我所示的固定值。

关于swift - 如何创建一个闭包来返回哪个参数为 true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37715621/

相关文章:

swift - NSFetchedResultsController 触发的动画完成后执行代码

arrays - Swift,如何从数组中删除一系列元素

ios - Swift Metal Compute Shaders 提供意想不到的混合结果

ios - SpriteKit 场景转换 XCode 7

macos - 使用 NSArrayController 时得到 "valueForUndefinedKey: this class is not key value coding-compliant for the key error"

ios - 'FIRAppNotConfigured',原因 : 'Failed to get default Firebase Database instance. Must call ` [FIRApp configure ]` (` FirebaseApp. configure()`(Swift 中)

php - Swift:使用 Alamofire 从 MYSQL 获取 JSON 数组值

ios - 不使用静态数据时 UIPageViewController 崩溃

iOS 9 - Xcode : "Follows Readable Width" programmatically

swift - compactMap 与 flatMap,Swift