swift - 类型 'NSArray?.Type' 不符合协议(protocol) 'Sequence'

标签 swift

从 Objective-C 转换后,我在 Swift 中遇到问题。谁能帮我解决这个问题?

var panels = NSArray?

func buttonTotalWidth() -> CGFloat {
        var width: CGFloat = 0
        for panel: UIView? in panels {
            width += panel?.frame.width
        }
        return width
    }

我的 objective-c 代码

@property NSArray *panels;

- (CGFloat)buttonTotalWidth {
    CGFloat width = 0;
    for (UIView *panel in self.panels) {
        width += CGRectGetWidth(panel.frame);
    }
    return width;
}

Error Screen

最佳答案

请不要尝试将 ObjC 代码逐字翻译成 Swift。学习 Swift 特定的东西。

一个 swift 的翻译可能是

var panels = [UIView]()

func buttonTotalWidth() -> CGFloat {
    return panels.map{$0.frame.width}.reduce(0.0, + )
}

关于swift - 类型 'NSArray?.Type' 不符合协议(protocol) 'Sequence',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50123588/

相关文章:

ios - 按需资源上是否允许存档文件?

ios - 安全区域与 iOS9/10/11 兼容 - 以编程方式

ios - 在 Swift 中展开 Optional Int

ios - MLMultiArray 使用未声明的类型错误

swift - 使用 swift 将结果附加到数据源

iphone - viewcontroller 容器的模拟宽度 View 小于嵌入式 tableview Controller 宽度

objective-c - tvOS 中禁止使用 AVSampleBufferDisplayLayer

ios - 快速删除xcode核心数据模型中的数据

ios - 存储为变量的函数会导致引用循环?

ios - 将两个文本字段文本保存在一个let中