【问题标题】:Accessing variable out completion block访问变量输出完成块
【发布时间】:2020-03-31 19:43:22
【问题描述】:

如何访问完成块之外的员工值,以便在ViewController 中的任何位置使用它

extension TabsParentViewController{
    class func checkCreateTabPermission(completion: @escaping PermCompletionWithCancel){
        RRS.s.permissionService.checkForPermission(.createTab, completion: { (pass, employee, cancel) in
            if !cancel {
                ActivityLogsBuilder.logActivity(forEmployee: employee, module: .tabs, action: ActivityLogsBuilder.action(from: LogAction.createTab, authorized: pass))
            }
            completion(pass, employee, cancel)
        })
    }
}

【问题讨论】:

  • 究竟是什么原因导致无法做到?
  • 例如,我有一个函数,它接受员工输入并在上述函数之外的某个地方调用,例如 x.func(employee: "这里我需要传递完成员工结果") 但实际上如何访问员工结果?
  • 我只能访问封闭内部的员工,但我需要它在外面
  • 很明显PermCompletionWithCancel 它是一个类型别名,其中包含员工作为其参数之一;你试过打电话给checkCreateTabPermission吗?看起来怎么样?
  • 是的,它是 typealias PermCompletionWithCancel = ((Bool, Employee?, Bool) -> Void)

标签: swift closures completionhandler


【解决方案1】:

默认调用checkCreateTabPermission为:

checkCreateTabPermission { pass, employee, cancel in
    // here you can use the `employee`
}

应该使您能够访问返回的employee。所以,你可以在checkCreateTabPermissioncompletion里面调用需要的方法:

checkCreateTabPermission { pass, employee, cancel in
    myMethod(employee: employee)
}

或者,如果您想在completion 之外访问员工,您可以声明一个变量(默认为nil)以在它返回后保持其值:

var myEmployee: Employee?

checkCreateTabPermission { [weak self] pass, employee, cancel in
    self?.myEmployee = employee
}

// you could use `myEmployee` here, but you have to make sure its not nil,
// in other words, `checkCreateTabPermission` has been called and retrieved one.
if let myUnwrappedEmployee = myEmployee {
    // use `myUnwrappedEmployee`...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多