iosswiftswift-optionals

How to safely unwrap an optional when filtering


Currently I have a snippet of code that uses a bam operator but it needs to be unwrapped:

 if let tagIds = location.tagIds, !filterSet.matchesTags(tagIds as! [String]) {
            return false
        }

I tried using a guard:

  guard  let tagIds = location.tagIds, let tapgIdsString = tagIds as? [String] else {return}, !filterSet.matchesTags(tapgIdsString) {
            return false
        }

but it causes an error, "non-void function should return a value"


Solution

  • Hard to answer without knowing how everything is declared, but it sounds like you could say

    if let tagIds = location.tagIds as? [String], !filterSet.matchesTags(tagIds)