การสร้างตัวดำเนินการมัดด้วยพารามิเตอร์

ขณะนี้ ฉันกำลังพยายามปรับปรุงเธรดพื้นหลังให้เป็นการดำเนินการเธรดหลักในแอปพลิเคชันของฉัน

วิธีที่ฉันทำคือ:

import Foundation

infix operator ~> {}

private let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)

func ~> (backgroundClosure: () -> (), mainClosure: () -> ()) {
    dispatch_async(queue) {
        backgroundClosure()
        dispatch_async(dispatch_get_main_queue(), mainClosure)
    }
}

ซึ่งจะให้ฉันทำสิ่งที่ชอบ:

{ println("executed in background thread") } ~> { println("executed in main thread") }

ตอนนี้... ฉันต้องการขยายฟังก์ชันนี้เพื่อให้สามารถ dispatch_after ไปยังเธรดหลักได้ ดังนั้นบางทีฉันอาจต้องการให้มันถูกเรียกในภายหลัง 0.25 วินาทีหรืออะไรสักอย่าง

มีวิธีใดที่จะบรรลุเป้าหมายนี้โดยส่งพารามิเตอร์หรือไม่?

ตามหลักการแล้ว ฉันจะสามารถใช้บางอย่างเช่น backgroundClosure ~>(0.25) mainClosure ได้ แต่ฉันสงสัยว่าจะเป็นไปได้


person David    schedule 14.10.2015    source แหล่งที่มา


คำตอบ (2)


เพียงข้อเสนอแนะ:

infix operator ~> {}

private let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)

func ~> (backgroundClosure: () -> (), secondParam: (delayTime:Double, mainClosure: () -> () )) {
    // you can use the `delayTime` here
    dispatch_async(queue) {
        backgroundClosure()
        dispatch_async(dispatch_get_main_queue(), secondParam.mainClosure)
    }
}

วิธีใช้:

{ print("executed in background thread") } ~> (0.25, { print("executed in main thread") })
person t4nhpt    schedule 15.10.2015
comment
โอ้ นี่เป็นความคิดที่ดีจริงๆ ฉันจะลองดู - person David; 16.10.2015

ลองสิ่งนี้:

private let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)

infix operator ~>{ associativity left precedence 140}

func ~> (backgroundClosure: ()->() , mainClosure: ()->()) {
dispatch_async(queue) { () -> Void in
    backgroundClosure()
    dispatch_async(dispatch_get_main_queue(), { () -> Void in
        mainClosure()
    })
}}
person Vandilson Lima    schedule 15.10.2015