[英]passing a global variable to a closure
I'm trying to implement sorting based on action sheet choice, where the sorting happens in the handler, but I can't pass the array i want to sort to the handler.我正在尝试根据操作表选择实现排序,排序发生在处理程序中,但我无法将要排序的数组传递给处理程序。 Here is my code:这是我的代码:
let byWage = UIAlertAction(title: "By Wage", style: UIAlertActionStyle.Default, handler: { action in
unclaimedJobs.sort() { $0.wage > $1.wage }
})
where unclaimedJobs
is a global variable.其中unclaimedJobs
是一个全局变量。 What's the best way to do this?做到这一点的最佳方法是什么?
Edit: This where I declare unclaimedJobs
:编辑:这是我声明unclaimedJobs
:
class JobsListViewController: UITableViewController, UITableViewDataSource {
var jobsList: JobsList!
var unclaimedJobs: [Job]!
I initialize it in viewDidLoad()
.我在viewDidLoad()
初始化它。
Edit#2: I understand you need a UIAlertAction
to be passed to the closure, so I replaced (unclaimedJobs)
with action.
编辑#2:我知道您需要将UIAlertAction
传递给闭包,因此我将(unclaimedJobs)
UIAlertAction
(unclaimedJobs)
替换为action.
Last Edit: I fixed this by putting self.unclaimedJobs
instead of unclaimedJobs.
最后编辑:我通过放置self.unclaimedJobs
而不是self.unclaimedJobs
来解决这个问题unclaimedJobs.
Not 100% sure.不是 100% 确定。 But I think it's this.但我认为就是这个。
let byWage = UIAlertAction(title: "By Wage", style: .Default, handler: {(alert: UIAlertAction!) in unclaimedJobs.sort({$0 > $1}) })
If you refer to an object inside a closure, you need an explicit reference to it.如果在闭包中引用一个对象,则需要对其进行显式引用。 In your case it's probably - self: like in self.unclaimedJobs.在您的情况下,它可能是 - self: 就像在 self.unclaimedJobs 中一样。 However, you have to unown this object like [unowned self] inside the closure, otherwise you'll have a memory leak.但是,您必须像在闭包中的 [unowned self] 一样取消拥有此对象,否则会出现内存泄漏。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.