IOS Xcode Swift autocomplete?

I haven't used Swift so much, but based on Objective-C, there are a few things about Swift that PITA is cheating on.

In iOS programming, we have the animateWithDuration: method, which is part of the UIView.

So, I tried using Xcode autocomplete and started typing:

 UIView.animateWith 

Autocomplete shows:

 UIView.animateWithDuration(duration: NSTimeInterval, animations: () -> Void) 

Then I moved to the "duration" field, and then dialed the number:

 UIView.animateWithDuration(0.5, animations: () -> Void) 

Then I again moved to the animation block and pressed the enter button, as usual, in Objective-C, now Xcode shows:

 UIView.animateWithDuration(0.5, animations: { () -> Void in code }) 

So, I last time put a tab to replace the "code" with my code:

 UIView.animateWithDuration(0.5, animations: { () -> Void in self.customView?.transform = CGAffineTransformMakeTranslation(0.0, 0.0); }) 

What when Xcode then gives me an error:

Cannot call 'animateWithDuration' using argument list of type '(FloatLiteralConvertible, animation :() -> Void)'

I do not understand. What is the autocomplete code that Xcode generated for me, why does it give me an error?

I noticed if you make a simple statement like:

 UIView.animateWithDuration(0.5, animations: { () -> Void in var num = 1 + 1; }) 

This does not give me any errors.

Any ideas anybody?

+5
source share
1 answer

From "Methods of calling through an optional chain" :

Any attempt to set a property through an optional chain returns a value of type Void? , which allows you to compare with nil to see if the property was successfully set ...

Therefore the type of expression

 self.customView?.transform = CGAffineTransformMakeTranslation(0.0, 0.0) 

- Void? (optional void). And if the closure consists of only one expression, then this expression is automatically accepted as the return value. The error message is pretty misleading, but it assumes that Void? different from Void .

Adding an explicit return solves the problem:

 UIView.animateWithDuration(0.5, animations: { () -> Void in self.customView?.transform = CGAffineTransformMakeTranslation(0.0, 0.0) return }) 

Update: Adding an explicit return not necessary anymore with Swift 1.2 (Xcode 6.3). From the beta notes:

In Void contexts, you can now use single-expression human closures with non-invasive return types.

+6
source

Source: https://habr.com/ru/post/1207812/


All Articles