Dan Beaulieu Dan Beaulieu - 1 year ago 88
Swift Question

Converting a Swift Completion Closure to C#

I'm porting a library from Swift to C# and I'm having trouble converting a completion handler to C#.

In Swift I have:

public typealias myChangeHandler = (progress: Double, myView: MyCustomView)

private var myChangeClosure: myChangeHandler?

public func myChangeClosure(_ completion: myChangeHandler) {
myChangeClosure = completion

Which can be called like this:

myChangeClosure?(progress: myProgress, view: self)

or like this:

localInstance.myChangeClosure() {
(progress: Double, myView: MyCustomView) in
textLabel.text = "\(Int(progress * 100.0))%"

In C#, I've attempted the same like this:

Func<double, CircularProgress> MyChangeType;

public void MyChangeClosure(Func<double, MyCustomView> completion)
MyChangeType = completion;

Which I am unable to call using similar syntax to Swift:

MyChangeType(myProgress, (MyCustomView)this); // bad job :'(

My Question

How can I convert the Swift completion functionality above to C#?

Answer Source

The Func first generic is the return type, which is the double in your case. What you want is to use an Action :

Action<double, CircularProgress> MyChangeType;

Then you can use it just like you want to :

MyChangeType(myProgress, (MyCustomView)this); // good job :)

You can take a look at this webpage for further explanation :


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download