类型'NSArray?.Type'不符合协议'序列'

时间:2018-05-01 20:46:15

标签: 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
    }

我的目标C代码

@property NSArray *panels;

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

Error Screen

2 个答案:

答案 0 :(得分:4)

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

swifty 翻译可能是

var panels = [UIView]()

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

答案 1 :(得分:0)

此方法接受UIView数组(而不是可选的UIVIew),试试这个

var panels = self.view.subviews
var width = buttonTotalWidth(panels)

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

如果这些是可选的UIViews,试试这个,

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