简体   繁体   English

在主线程槽自定义运算符上快速执行关闭

[英]Swift execute closure on main thread trough custom operator

Apparently Xcode doesn't let me modify the UI (iOS) from a background thread. 显然,Xcode不允许我从后台线程修改UI(iOS)。 I have to type: 我必须输入:

let res = somethingReturningaString()
dispatch_async(dispatch_get_main_queue(), {
        self.txtError.text = res!
})

My idea was: 'hey, let's simplify my life and define a custom operator, so I can type something like:' 我的想法是:“嘿,让我们简化生活并定义一个自定义运算符,这样我就可以输入:

prefix operator ~> {}

prefix func ~> (closure: ()-> ()) {
    dispatch_async(dispatch_get_main_queue(), closure)
}
//usage example
~> {self.txtError.text = res!}

Apparently the operator of type '()' cannot be applied to '()->()' Does anybody know how to declare this to get this working? 显然类型'()'的运算符不能应用于'()->()',有人知道如何声明它来使它起作用吗?

The swift compiler got a little confused there. 敏捷的编译器在那里有些困惑。 You must not ever separate a unary operator from its operand, meaning there must not be a whitespace in between. 您绝对不能将一元运算符与其操作数分开,这意味着两者之间一定不能有空格

Consider the following example code 考虑以下示例代码

let k = 12
~> {
    self.txtError.text = res!
}

Swift now expects ~> to be a binary operand because there is a whitespace. Swift现在期望~>是一个二进制操作数,因为存在空格。

binary operator '~>' cannot be applied to operands of type 'Int' and '() -> ()' 二进制运算符'〜>'不能应用于'Int'和'()->()'类型的操作数

If you insert a ; 如果插入; after the first line: 第一行之后:

let k = 12;
~> {
    self.txtError.text = res!
}

You receive something a little bit more helpful: 您会得到一些帮助:

Unary operator cannot be separated from its operand 一元运算符不能与其操作数分开

Which simply means that there must in fact be no whitespace. 这仅意味着实际上必须没有空格。

Fix 固定

Remove the whitespace: 删除空格:

~>{ self.txtError.text = res! }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM