简体   繁体   English

嵌套自执行闭包

[英]Nested self executing closures

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.我正在尝试嵌套一些自执行闭包,但我遇到了一个奇怪的编译器错误(“nil”与返回类型“NSPredicate”不兼容),我认为这是因为嵌套的自执行闭包,但我不是当然,我在搜索时找不到任何相关内容。

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)
    }()
}

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:您可以将nil更改为.none ,您将看到一个非常明显的错误:

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

Similarly, within preferredLanguagePredicate , does Locale.preferredLanguageCode actually exist?同样,在preferredLanguagePredicate中, Locale.preferredLanguageCode真的存在?

The error code is kind of confusing, this is not about the nil value.错误代码有点令人困惑,这与 nil 值无关。 If you use Date in NSPredicate you need to cast it to NSDate .如果您在NSPredicate中使用Date ,则需要将其转换为NSDate

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM