Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
316 views
in Technique[技术] by (71.8m points)

Swift How To - First/Where statement checking array of optional objects - unwrap and match

I have an array of objects that are all of class PFObject. I have a subclass of PFObject called GameCategory where some of the PFObjects in my array are GameCategory.

I was wondering how to write a first/where statement that would check each object to see if it is of class GameCategory, then check for a matching ID.

Here is my non-working attempt to do this:

for id in Ids {
    if let object = self.matchObjects.first(where: {
        if let gameCategory = $0 as? GameCategory {
            gameCategory.id == id
        }
    }) {
        //object successfully cast as GameCategory, and the GameCategory id was a match            
    }
}

This code returns the error 'Missing return in a closure expected to return 'Bool'.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your code is missing the return in that first(where: closure and casting as GameCategory (your cast is only existing in the scope of that closure). I wrote it a little bit different but it will achieve the same:

for id in Ids {
    if let object = self.matchObjects.first(where: { ($0 as? GameCategory)?.id == id }) as? GameCategory {
        //object cast as GameCategory and the id was a match
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...