animateWithDuration:动画:完成:在Swift中

Nil*_*ne- 8 closures animatewithduration swift ios8

在objective-C中,我的动画位看起来像这样:

[UIView animateWithDuration:0.5 animations:^{
            [[[_storedCells lastObject] topLayerView] setFrame:CGRectMake(0, 0, swipeableCell.bounds.size.width, swipeableCell.bounds.size.height)];
        } completion:^(BOOL finished) {
            [_storedCells removeLastObject];
 }];
Run Code Online (Sandbox Code Playgroud)

如果我将其翻译成Swift,它应该看起来像这样:

 UIView.animateWithDuration(0.5, animations: {
                    self.storedCells[1].topLayerView.frame = CGRectMake(0, 0, cell.bounds.size.width, cell.bounds.size.height)
                }, completion: { (finished: Bool) in
                    //self.storedCells.removeAtIndex(1)
            })
Run Code Online (Sandbox Code Playgroud)

它在评论线上抱怨.我收到的错误是:Could not find an overload for 'animateWithDuration' that accepts the supplied arguments

我知道完成闭包需要一个布尔值并返回一个void,但是我应该能够写出一些与bool无关的东西....对吧?

任何帮助表示赞赏.

编辑:这是我如何在函数中声明我正在使用的数组:

var storedCells = SwipeableCell[]()
Run Code Online (Sandbox Code Playgroud)

一个采用SwipeableCell对象的数组.

fqd*_*qdn 8

这是一个很好的,很棘手!

问题在于你的完成块......

:我会先重写它:( 不是最终的答案,但在我们的路上!)

{ _ in self.storedCells.removeAtIndex(1) }

(_代替"完成"Bool,向读者表明其值未在块中使用 - 您还可以考虑添加捕获列表以防止强引用周期)

B.你写的封口有一个不应该的退货类型!所有这一切都归功于Swift的便捷功能"单个表达式闭包的隐式返回" - 您将返回该表达式的结果,该表达式是给定索引处的元素

(闭包参数的类型completion应为((Bool) - > Void))

这可以解决如下:

{ _ in self.storedCells.removeAtIndex(1); return () }

  • Swift有一个功能,它将自动返回只包含单个表达式的闭包的值,而不必专门使用'return'关键字 - 它意味着允许更可读和更简洁的代码 - 但在这种情况下,它正在绊倒你,因为方法'removeAtIndex'有一个返回值:它删除的项目!这是闭包中唯一的表达式,Swift从块中返回_that_值!但是,该块应该具有返回类型'Void' - 所以我们手动返回'()'以符合闭包的类型 (2认同)
  • @rickster从Xcode 6.1 beta 2开始,你不能使用"return Void"."return()"和"return"都可以正常工作.恕我直言"返回"更具可读性,因为它与C/ObjectiveC中的等效内容相匹配 - YMMV! (2认同)