Cannot convert type 'Void' to 'String' in coercion in Swift

1k views Asked by At

So i'm using some libraries and one of the methods, has supposedly return value

let data2 = dataCollector.collectCardFraudData({ ( str:String) in })

But the problem is that the return value is of void type but i could see the value present in it, i've checked a lot of tutorials where they have suggested to change the return type, but since this being a library i don't think i can do that.Is there any other way to get that value converted to string ??

I'm also kinda new Swift, so please any inputs would be helpfull

Thanks

3

There are 3 answers

0
vadian On BEST ANSWER

The function has no return value. The Swift equivalent is

func collectCardFraudData(completion: @escaping (String) -> Void)

So you have to call it with the syntax below. deviceData is passed as a parameter and you have to call completion when you're done.

dataCollector.collectCardFraudData { deviceData in 

  // do something with deviceData
  completion()
}
0
Mohammad Sadiq On

I don't know much. Just the guess. Your function is returning the value via completion handler. You should use it like this

let data2 = dataCollector.collectCardFraudData({ str in
    print(str) // str available here
})
1
Manish Patel On

As collectCardFraudData has a closure where it give you 'str' value inside that block direct assigning it to 'data2' is causing you error.

Try below code and please let me know if it works

var data2 = String()
dataCollector.collectCardFraudData({ str in 
    data2 = "\(str)"
})

Thank you