-2

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

burnsi
  • 6,194
  • 13
  • 17
  • 27
smack
  • 1
  • I saw a developer Crete an extension which provided a func with the “default to nil” arguments missing, the extension would then pass nil to the protocol func – MadProgrammer Jun 17 '22 at 23:40

1 Answers1

1

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]? {
... 
    }
}
Paulw11
  • 108,386
  • 14
  • 159
  • 186
  • Still its asking predicate while using then function for eg: CoreDataProvider.shared.fetchData(entity:Student.self,entityName:"Student") but it still shows predicate parameter is missing – smack Jun 17 '22 at 07:02
  • 1
    You almost certainly don't want `expressibleByNilLiteral` on your protocol definition. The code in my answer works for me. Xcode will still suggest the `predicate` argument when you use the function but you don't need it – Paulw11 Jun 17 '22 at 07:12