2014-08-28 128 views
0

我想知道如何将下面转换成Swift。我曾经尝试过,但都得到了停留在一个概念:转换enumerateObjectsUsingBlock快速Enemuration - 斯威夫特

我通过我的所有对象与我属性 UICollectionViewLayoutAttributes

循环
[newVisibleItems enumerateObjectsUsingBlock:^(UICollectionViewLayoutAttributes *attribute, NSUInteger idx, BOOL *stop) { 
    UIAttachmentBehavior *spring = [[UIAttachmentBehavior alloc] initWithItem:attribute attachedToAnchor:attribute.center]; 
    spring.length = 0; 
    spring.frequency = 1.5; 
    spring.damping = 0.6; 

    [_animator addBehavior:spring]; 
    [_visibleIndexPaths addObject:attribute.indexPath]; 
}]; 

斯威夫特:变量标*是得到一个错误:

for (index, attribute) in enumerate(newVisibleIems) { 
    var spring:UIAttachmentBehavior = UIAttachmentBehavior(item: ***attribute***, attachedToAnchor: attribute.center) 

    spring.length = 0 
    spring.frequency = 1.5 
    spring.damping = 0.6 

    self.animator.addBehavior(spring) 
    self.visibleIndexPaths.addObject(attribute.indexPath) 
} 

***类型 'AnyObject' 不符合协议 'UIDynamicItem'

我认为这是因为我没有告知属性这是一个UICollectionViewLayoutAttributes。但我不确定如何写这个?

本质上,如何将Objective C转换为Swift?

回答

1

只要newVisibleItems声明为[AnyObject],由于Swift严格的类型检查,您的代码将无法编译。

为了确保newVisibleItems预计类型的数组,你要包装你for循环向下转换中:

if let newVisibleItems = newVisibleItems as? [UIDynamicItem] { 
    for (index, attribute) in enumerate(newVisibleItems) { 
     ... 
    } 
} 

如果里面的UIKit此错误的原因奠定了,放心,苹果现在正在努力确保其框架的“swiftified”版本中的每个声明都返回正确的类型,而不是AnyObject!的组合。