Swift忽略块签名中定义的参数类型

Swift忽略块签名中定义的参数类型,swift,nspredicate,swift-block,swift-optionals,Swift,Nspredicate,Swift Block,Swift Optionals,我有下面的代码,编译器很满意: func CheckPaintExists(colorCode : String, applicationCode : String) { let checkRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Paint") checkRequest.predicate = NSPredicate(block: { (item, bindings) -> Bool

我有下面的代码,编译器很满意:

func CheckPaintExists(colorCode : String, applicationCode : String) {
    let checkRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Paint")
    checkRequest.predicate = NSPredicate(block: { (item, bindings) -> Bool in
        return (item as! Paint).ColorCode == colorCode 
            && (item as! Paint).ApplicationCode == applicationCode
    })
    checkRequest.includesSubentities = false;

    //managedContext.count(for: ...)do further stuff
}
它表示类型为“Any”的
值没有成员“ColorCode”
。我如何解决这个问题?为什么它仍然使用块提供的默认Any类型?

如果查看for
NSPredicate.init(块:)
,您将看到该块接受两个参数并返回一个布尔值:
(Any?,[String:Any]?)->Bool)
,第一个参数实际上是
Any

在您的第一个示例中,您正在使用
强制转换为这就是它工作的原因(如果类型实际上不是
Any
中的
Paint
框,那么它会在这里崩溃。您的第二个示例给出了一个错误,因为您的类型注释是错误的;编译器希望第一个参数是
Any
,而不是
Paint?
;它确实应该在上面一行给出错误,但似乎是错误的。)it’我们先在回程线上接它

如果要安全地展开,应:

func CheckPaintExists(colorCode : String, applicationCode : String) {
    let checkRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Paint")
    checkRequest.predicate = NSPredicate(block: { (item, bindings) -> Bool in
        guard let paint = item as? Paint else {
           return false
        }
        return paint.ColorCode == colorCode 
            && paint.ApplicationCode == applicationCode
    })
    checkRequest.includesSubentities = false;

    //managedContext.count(for: ...)do further stuff
}
func CheckPaintExists(颜色代码:String,应用程序代码:String){
让checkRequest=NSFetchRequest(entityName:“绘制”)
checkRequest.predicate=NSPredicate(块:{(项,绑定)->Bool-in
防护罩油漆=项目为?油漆其他{
返回错误
}
return paint.ColorCode==ColorCode
&&paint.ApplicationCode==应用程序代码
})
checkRequest.includesSubentities=false;
//count(for:…)执行进一步的操作
}

奇怪的是,当我点击项目上的
点时,Xcode autocomplete/建议实际上会显示/建议绘画属性。这意味着它会将项目视为绘画类型。一旦我点击enter放置属性,它就会抱怨。我刚发现这很奇怪。我确实想过安全地展开
项目
,但我想我自己小精灵,我肯定知道
物品
将是油漆类型的,安全地拆开它对我来说似乎很麻烦。他们说swift比swift编码少,我说事实正好相反。我想这是另一个车队的主题。干杯
func CheckPaintExists(colorCode : String, applicationCode : String) {
    let checkRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Paint")
    checkRequest.predicate = NSPredicate(block: { (item, bindings) -> Bool in
        guard let paint = item as? Paint else {
           return false
        }
        return paint.ColorCode == colorCode 
            && paint.ApplicationCode == applicationCode
    })
    checkRequest.includesSubentities = false;

    //managedContext.count(for: ...)do further stuff
}