gpt4 book ai didi

ios - 将 enumerateObjectsUsingBlock 转换为快速枚举 - Swift

转载 作者:行者123 更新时间:2023-11-29 02:42:44 25 4
gpt4 key购买 nike

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

我正在使用我的属性 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”不符合协议(protocol)“UIDynamicItem”

我想这是因为我没有告诉项目 attribute 那是一个 UICollectionViewLayoutAttributes。但是不确定如何写这个?

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

最佳答案

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

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

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

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

关于ios - 将 enumerateObjectsUsingBlock 转换为快速枚举 - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25548083/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com