【问题标题】:Transform enumerateObjectsUsingBlock to Fast Enemuration - Swift将 enumerateObjectsUsingBlock 转换为快速枚举 - Swift
【发布时间】:2014-08-28 11:50:33
【问题描述】:

我想知道如何将以下内容转换为 Swift。我已经尝试过了,但陷入了一个概念:

我正在使用我的 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:标记为 * 的变量出现错误:

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”

我认为这是因为我没有告诉项目 attribute 是 UICollectionViewLayoutAttributes。但是不知道怎么写?

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

【问题讨论】:

    标签: ios objective-c swift enumerate fast-enumeration


    【解决方案1】:

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

    为确保 newVisibleItems 是预期类型的​​数组,您必须将 for 循环包装在向下转换中:

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

    如果此错误的原因在于 UIKit 内部,请放心,Apple 目前正在努力确保其框架的“swiftified”版本中的每个声明都返回正确的类型,而不是 AnyObject! 的组合秒。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-07
      • 2020-08-21
      • 2021-01-04
      • 1970-01-01
      • 1970-01-01
      • 2015-12-10
      相关资源
      最近更新 更多