Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[GCD 和延时调用]里例子不够精简的小建议 #83

Open
copewang opened this issue May 8, 2018 · 0 comments
Open

[GCD 和延时调用]里例子不够精简的小建议 #83

copewang opened this issue May 8, 2018 · 0 comments

Comments

@copewang
Copy link

copewang commented May 8, 2018

书里说到要点,用cancel标识变量,但是,把例子写复杂了

//---书中的代码---
func cancel(_ task: Task?) {
    //1.这里写死一个true的参数,是多余的,
    //2.如果这里是task?(false) 就是立即执行,从命名上来看,逻辑是不清晰的
    task?(true)
}

//----精简版---
typealias CancelTask = () -> ()
func delay(_ time: TimeInterval, task: @escaping ()->()) -> CancelTask {
    var isCancelled = false
    let cancelTask = {
        isCancelled = true;
    }
    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time) {
        if !isCancelled {
            task()
        }
    }
    
    return cancelTask;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant