在swift

时间:2016-03-06 08:47:01

标签: swift closures realm

我对如何运行以下代码感到有些失落。我的意图是只有在尝试成功时才执行onCompletion。那么延迟关闭应该在试验内还是之后呢? - 或者我完全走错了路。

此...

func addUserActivity(aUserActivity:UserActivity, onError:OnError, onCompletion: (Void) -> (Void)) {
        if let database = database {
            do {
                try database.write({
                    database.add(aUserActivity)
                    defer {
                        onCompletion()
                    }
                })
            } catch {
                onError(message: "Realm error",informativeText: "Realm database failed to write object")
            }
        }
    }

或者这......

func addUserActivity(aUserActivity:UserActivity, onError:OnError, onCompletion: (Void) -> (Void)) {
        if let database = database {
            do {
                try database.write({
                    database.add(aUserActivity)
                })
                defer {
                    onCompletion()
                }
            } catch {
                onError(message: "Realm error",informativeText: "Realm database failed to write object")
            }
        }
    }

还是完全不同的东西?

1 个答案:

答案 0 :(得分:1)

在任何一种情况下,都不需要defer。您只需撰写onCompletion()

即可

如果你在onCompletion()区块内拨打write总是会被执行,但如果你在try database.write{...}之后写,那么onCompletion将是如果write引发错误,则会跳过,这听起来像是您想要的行为。

(由OP编辑以包括最终解决方案)

<强>解

func addUserActivity(aUserActivity:UserActivity, onError:OnError, onCompletion: (Void) -> (Void)) {
        if let database = database {
            do {
                try database.write({
                    database.add(aUserActivity)
                })
                onCompletion()
            } catch {
                onError(message: "Realm error",informativeText: "Realm database failed to write object")
            }
        } 
    }