2014-08-28 49 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!的組合。