Skip to content

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

Description

@copewang

书里说到要点,用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;
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions