Home > database >  Nested self executing closures
Nested self executing closures

Time:01-21

I'm trying to nest some self executing closures but I'm getting a strange compiler error ('nil' is incompatible with return type 'NSPredicate') that I'm thinking it's because of the nested self executing closures but I'm not sure and I couldn't find anything relevant when searching for it.

public func fetch(lastFetchedTimestamp: Date?) async throws {
    let predicate: NSPredicate = {
            
            let isApprovedPredicate = NSPredicate(format: "isApproved == 1")
            let preferredLanguagePredicate: NSPredicate? = {
                guard let preferredLanguageCode = Locale.preferredLanguageCode else {
                    return nil
                }
                return .init(format: "language == %@", preferredLanguageCode)
            }()
            let modificationDatePredicate: NSPredicate? = {
                guard let lastFetchedTimestamp else {
                    return nil // <-- 'nil' is incompatible with return type 'NSPredicate' 
                }
                return .init(format: "modificationDate > %@", lastFetchedTimestamp)
            }()
            
            let predicates = [isApprovedPredicate, preferredLanguagePredicate, modificationDatePredicate].compactMap { $0 }
            
            return NSCompoundPredicate(andPredicateWithSubpredicates: predicates)
    }()
}

CodePudding user response:

Try breaking it to different part. For instance:

let modificationDatePredicate: NSPredicate? = {
    guard let lastFetchedTimestamp else {
        return nil
    }
    return .init(format: "modificationDate > %@", lastFetchedTimestamp)
}()

You can change nil to .none, and you will see a pretty clear error:

return .init(format: "modificationDate > %@", lastFetchedTimestamp)
                                              ^^^^^^^^^^^^^^^^^^^^
// Argument type 'Date' does not conform to expected type 'CVarArg'

Similarly, within preferredLanguagePredicate, does Locale.preferredLanguageCode actually exist?

CodePudding user response:

The error code is kind of confusing, this is not about the nil value. If you use Date in NSPredicate you need to cast it to NSDate.

return .init(format: "modificationDate > %@", lastFetchedTimestamp as NSDate)
  • Related