I'm wondering how to transform the following below into Swift. I have attempted it, but have gotten stuck on a concept:
I am looping through all my objects with my attribute 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];
}];
Swift: The Variable marked * is getting an error:
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)
}
***Type 'AnyObject' does not conform to protocol 'UIDynamicItem'
I assume it is because I haven't told the item attribute that is is a UICollectionViewLayoutAttributes. But am unsure how to write this?
Essentially, how to I transform the Objective C to Swift?
As long as newVisibleItems is declared as [AnyObject]
, your code won't compile due to Swift's strict type checking.
To ensure newVisibleItems
is an array of expected types, you have to wrap your for
loop inside a downcast:
if let newVisibleItems = newVisibleItems as? [UIDynamicItem] {
for (index, attribute) in enumerate(newVisibleItems) {
...
}
}
If the reason of this error lays inside UIKit, be assured that Apple is working hard right now to ensure that every single declaration in the "swiftified" version of their frameworks returns a proper type, instead of a combination of AnyObject!
s.