传递协议功能的零值(SWIFT)

发布于 2025-02-08 01:04:00 字数 644 浏览 1 评论 0原文

我想在协议的函数中传递零值,但协议会出现错误:“默认参数不允许在协议方法中”。

protocol CoreDataRepositoryProtocol: ExpressibleByNilLiteral{
    func fetchData<T:NSManagedObject>(entity: T.Type, enityName: entittytype, predicate: NSPredicate? = nil) -> [T]?
    func getOne   <T:NSManagedObject>(entity: T.Type, enityName: String, predicate: NSPredicate) -> T?
    func deleteRec<T:NSManagedObject>(entity: T.Type, entityName:entittytype, predicate: NSPredicate, completion: @escaping (String) -> Void) -> Bool
    func saveObject()
}

第一个函数,我想添加谓词为predicate:nspredicate:nspredicate?= nil nil 但是协议不接受

I wanted to pass nil value in a function of protocol but protocol gives error: "Default argument not permitted in a protocol method"

protocol CoreDataRepositoryProtocol: ExpressibleByNilLiteral{
    func fetchData<T:NSManagedObject>(entity: T.Type, enityName: entittytype, predicate: NSPredicate? = nil) -> [T]?
    func getOne   <T:NSManagedObject>(entity: T.Type, enityName: String, predicate: NSPredicate) -> T?
    func deleteRec<T:NSManagedObject>(entity: T.Type, entityName:entittytype, predicate: NSPredicate, completion: @escaping (String) -> Void) -> Bool
    func saveObject()
}

The first function , I want to add predicate as predicate:NSPredicate?=nil but protocol is not accepting

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

嗼ふ静 2025-02-15 01:04:00

正如错误所说,您无法在协议中提供默认值。

您的协议可以声明

func fetchData<T:NSManagedObject>(entity: T.Type,enityName: entittytype,predicate:NSPredicate?)

您可以在编写符合此协议的对象时提供nil的默认值

class CoreDataProvider: CoreDataRepositoryProtocol {

    func fetchData<T:NSManagedObject>(entity: T.Type,enityName: entittytype,predicate:NSPredicate?=nil) -> [T]? {
... 
    }
}

As the error says, you can't provide a default value in the protocol.

Your protocol can declare

func fetchData<T:NSManagedObject>(entity: T.Type,enityName: entittytype,predicate:NSPredicate?)

You can provide a default value of nil when you write implement an object that conforms to this protocol

class CoreDataProvider: CoreDataRepositoryProtocol {

    func fetchData<T:NSManagedObject>(entity: T.Type,enityName: entittytype,predicate:NSPredicate?=nil) -> [T]? {
... 
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文