Siva
Siva

Reputation: 1858

Type 'NSArray?.Type' does not conform to protocol 'Sequence'

I am facing issue in Swift after converting from Objective-C. Can anyone help me to fix this issue?

var panels = NSArray?

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

My Objective C code

@property NSArray *panels;

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

Error Screen

Upvotes: 1

Views: 276

Answers (2)

Jay
Jay

Reputation: 864

This method accepts the array of UIView(and not optional UIVIew), try this

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
}

if those are some optional UIViews, try this,

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

Upvotes: 0

vadian
vadian

Reputation: 285132

Please don't try to translate ObjC code literally to Swift. Learn the Swift specific stuff.

A swifty translation could be

var panels = [UIView]()

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

Upvotes: 4

Related Questions