softbear
softbear

Reputation: 515

Multiple use of same closure argument won't compile

Why is it not compiling the following:

extension Array {

    func firstWhere(fn: (T) -> Bool) -> T? {
        for x in self {
            if fn(x) {
                return x
            }
        }
        return nil
    }
}

var view = UIView()
// Do setup here of view if you want (but shouldn't be necessary)

let x = view.subviews.firstWhere { $0.tag? == 1 && $0.userInteractionEnabled } as? UIView

Compiler is saying: Could not find member 'userInteractionEnabled'

Upvotes: 0

Views: 78

Answers (1)

Dániel Nagy
Dániel Nagy

Reputation: 12015

Because the type of view.subviews is [AnyObject], so you have to cast it to [UIView] first to have userInteractionEnabled. So:

(view.subviews as! [UIView]).firstWhere( ... )

And I'm not sure which version of Xcode you are using, but this (I mean that the question mark at the end of tag is not needed):

let x = (view.subviews as! [UIView]).firstWhere { $0.tag == 1 && $0.userInteractionEnabled }

compiles fine in Xcode 6.3 .

Upvotes: 1

Related Questions