gcd的封裝(swift)

來源:互聯網
上載者:User

標籤:ios   swift   gcd   

gcd的封裝(swift)by 伍雪穎
overridefunc viewDidLoad() {
    delay(2) {
        println("2s later")
    }
    let task =delay(5) {
        println("call")
    }
    cancel(task)
}

typealias Task = (cancel :Bool) -> ()
func delay(time:NSTimeInterval,task:()->()) -> Task? {
    func dispatch_later(block:() -> ()) {
        dispatch_after(
            dispatch_time(
            DISPATCH_TIME_NOW,
            Int64(time *Double(NSEC_PER_SEC))),
            dispatch_get_main_queue(),
            block)
    }
    var closure:dispatch_block_t? = task
    var result:Task?
   
    let delayedClosure:Task = {
        cancel in
        iflet internalClosure = closure {
            if (cancel ==false) {
                dispatch_async(dispatch_get_main_queue(), internalClosure);
            }
        }
        closure = nil
        result = nil
    }
   
    result = delayedClosure
   
    dispatch_later {
        iflet delayedClosure = result {
            delayedClosure(cancel: false)
        }
    }
    return result;
}

func cancel(task:Task?) {
    task?(cancel: true)}

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

gcd的封裝(swift)

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.