Sean Cook
Sean Cook

Reputation: 435

Swift closure not working

I am trying to run a closure but am receiving an error. Cannot convert value of type '()' to closure result type 'Bool'. I'm not sure what I am doing wrong here.

func runPrintCycle(){
        self.runPrinter1() { success in
            self.runPrinter2() { success in
              print("Success")
            }
        }
    }

    func runPrinter1(completionHandler: (Bool) -> Bool){
        if let printer1 = Workstation.instance.printer1{
            let receiptPrinter = Print(printer: printer1)
            receiptPrinter.runPrinterReceiptSequence() { success in
                completionHandler(true)
            }
        }else{
            completionHandler(true)
        }
    }

func runPrinter2(completionHandler: (Bool) -> Bool){
            if let printer2 = Workstation.instance.printer2{
                let receiptPrinter = Print(printer: printer2)
                receiptPrinter.runPrinterReceiptSequence() { success in
                    completionHandler(true)
                }
            }else{
                completionHandler(true)
            }
        }

Upvotes: 1

Views: 970

Answers (1)

Yury
Yury

Reputation: 6114

You probably not need to declare completeon closures as returned Bool value in runPrinter functions. Make them return Void instead. Also you probably want to send false in closure when printer not found:

func runPrintCycle() {
    self.runPrinter1() { success in
        print("Printer 1: \(success)")
        // put here if(success) if you wish run second printer only on success
        self.runPrinter2() { success in
            print("Printer 2: \(success)")
        }
    }
}

func runPrinter1(completionHandler: (Bool) -> ()) {
    if let printer1 = Workstation.instance.printer1 {
        let receiptPrinter = Print(printer: printer1)
        receiptPrinter.runPrinterReceiptSequence() { success in
            completionHandler(true) //probably success instead true?
        }
    }else{
        completionHandler(false)
    }
}

func runPrinter2(completionHandler: (Bool) -> ()){
    if let printer2 = Workstation.instance.printer2{
        let receiptPrinter = Print(printer: printer2)
        receiptPrinter.runPrinterReceiptSequence() { success in
            completionHandler(true) //probably success instead true?
        }
    }else{
        completionHandler(false)
    }
}

Upvotes: 2

Related Questions