简体   繁体   中英

Swift execute closure on main thread trough custom operator

Apparently Xcode doesn't let me modify the UI (iOS) from a background thread. 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.

binary operator '~>' cannot be applied to operands of type 'Int' and '() -> ()'

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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