1
votes

I'm trying to implement Completion handlers but I'm getting this error:

cannot convert value of type to specified type.

Here is my code:

override func viewDidLoad() {
    super.viewDidLoad()
    let sss : String  = doSomethingElse { (data) in

    }
    print(sss)
}

func doSomethingElse(completion:(data:String) -> Void) {

    let s = "blablabla"

    print(s)
    completion(data:s)
}

On this line is where I'm getting the error:

let sss : String  = doSomethingElse { (data) in

enter image description here

Any of you knows why I'm getting this error?

I'll really appreciate your help.

1
Because you declared sss as a String and then tried to assign a closure to it.Paulw11

1 Answers

1
votes

You have declared sss to be a String but then you have attempted to assign a closure to it; so the compiler gives you an error.

I think what you were trying to do this assign the closure to sss and then pass this closure to doSomethingElse:

func viewDidLoad() {
    super.viewDidLoad()

    let sss : ((data:String) -> Void) = { data in
      print ("data is \(data)")
    }

    doSomethingElse(sss)
}

func doSomethingElse(completion:(data:String) -> Void) {

    let s = "blablabla"

    print(s)
    completion(data:s)
}

which will give the following output:

blablabla

data is blablabla