title: Check data exist before saving in coredata -Swift
body: <p>While saving the data am checking whether the data is already exist or not in the entity. Problem here is the above method is not working as expected, when I run the app for very first time it's showing data is already exist. Please check the below code and shed some light. Thanks.</p>
  
  <pre><code>func someEntityExists(id: String, entityName: String, type : String, fieldName : String) -&gt; Bool {
      let fetchRequest = NSFetchRequest&lt;NSManagedObject&gt;(entityName: entityName)
      if type == "String"{
      fetchRequest.predicate = NSPredicate(format: "\(fieldName) == %@", id)
      }else{
          fetchRequest.predicate = NSPredicate(format: "\(fieldName) == %d", id)
  
      }
  
      var results: [NSManagedObject] = []
  
      do {
          results = try self.persistentContainer.viewContext.fetch(fetchRequest)
      }
      catch {
          print("error executing fetch request: \(error)")
      }
  
      return results.count &gt; 0
  }
  </code></pre>
  
  <p>Below is the code where am calling this function to save the user information.</p>
  
  <pre><code>  func saveUserInfo(detail:[String:Any])-&gt; Bool
  {
      let context = self.persistentContainer.viewContext
      var isSave : Bool = false
      let entity = NSEntityDescription.entity(forEntityName: "User", in: context)
      let newUser = NSManagedObject(entity: entity!, insertInto: context)
      newUser.setValue(detail["id"], forKey: "id")
      newUser.setValue(detail["api_token"], forKey: "api_token")
      newUser.setValue(detail["username"], forKey: "username")
      newUser.setValue(detail["email"], forKey: "email")
      if let category = detail["firstname"] as? String {
          newUser.setValue(detail["firstname"], forKey: "firstname")
      }
      if let category = detail["middlename"] as? String {
          newUser.setValue(detail["middlename"], forKey: "middlename")
      }
      if let category = detail["lastname"] as? String {
          newUser.setValue(detail["lastname"], forKey: "lastname")
      }
  
      do {
  
          let isExist = someEntityExists(id: newUser.value(forKey:        "email") as! String , entityName: "User", type: "String", fieldName: "email")
          if isExist == true {
              // don't save anything
              print("Data is already present  ")
          }else{
          try context.save()
          isSave  = true
          }
      } catch {
  
          print("Failed saving")
          isSave  = false
      }
  
  
  
      return isSave
  
  }
  </code></pre>