Nil can't be assigned to type () -> ()?

So this is a function from the class that allows you to use double tap and one gesture gesture. It works great in Swift 2.3, but after converting to Swift 3, it throws a few errors. I cannot understand / understand all my life. I have commented where they are happening.

//  UIShortTapGestureRecognizer.swift
//
//

import Foundation
import UIKit


    func delayHelper(_ time:TimeInterval, task:@escaping ()->()) ->  DelayTask? {

        func dispatch_later(_ block:@escaping ()->()) {
            DispatchQueue.main.asyncAfter(
                deadline: DispatchTime.now() + Double(Int64(time * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC),
                execute: block)
        }

        var closure: ()->()? = task

        var result: DelayTask?

        let delayedClosure: DelayTask = {
            cancel in

//Initializer for conditional binding must have Optional type, not '() -> ()?'
            if let internalClosure = closure {
                if (cancel == false) {
                    DispatchQueue.main.async(execute: internalClosure)
                }
            }

// here it says Nil cannot be assigned to type '() -> ()?'
            closure = nil

            result = nil
        }

        result = delayedClosure

        dispatch_later {
            if let delayedClosure = result {
                delayedClosure(false)
            }
        }

        return result;
    }

    func cancel(_ task:DelayTask?) {
        task?(true)
    }
}

      

+3


source to share


3 answers


Try: var closure: (()->())? = task



+4


source


From another thread:

func someFunction(someParameter: someType, completionClosure: @escaping @autoclosure () -> ()? = nil)

      

Using @autoclosure allowed me to assign nil to the optional closure.

Full details of exactly how @autoclosure helps avoid me (why "my" closure is "not good" but Swift_generated_one_that_simply_wraps_mine?). But it helped me get rid of ... enter image description here  ... and call my function in one of two ways:



someFunction(x, { ... }) 

      

OR

someFunction(x)

      

0


source


Here's how I could get over it. Here clang is unaware of its type. I gave typealias and optional declaration,

typealias appDelegateBlock = ()->()

      

In your class, just declare it optional,

var block: appDelegateBlock?
block = task

      

0


source







All Articles