CoreData max value get

I tried to get the maximum value from coredata

func datMeetingMaxId() -> Int {

//*****context is DB file stored place
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

/// get max Variable declaration
let expressionDatMeetiongId = "Maxid"
///make fetchRequest
let fetchRequest = NSFetchRequest<NSFetchRequestResult>()

///make EntityDescription
//forEntityName is DB name
//open class func entity(ここ- forEntityName entityName: String, in context: NSManagedObjectContext) -> NSEntityDescription?
//in : context There is in context
let entityDescription = NSEntityDescription.entity( forEntityName :"DatMeeting" , in : context)

fetchRequest.entity = entityDescription

//********Make instance
let keyPathExpression = NSExpression(forKeyPath: "id")
let expression = NSExpression(forFunction: "max:", arguments: [keyPathExpression])
let expressionDescription = NSExpressionDescription() = expressionDatMeetiongId
expressionDescription.expression = expression
expressionDescription.expressionResultType = NSAttributeType.integer64AttributeType

fetchRequest.resultType = NSFetchRequestResultType.dictionaryResultType
fetchRequest.propertiesToFetch = [expressionDescription]

//******Error handling do try catch
let results = try context.fetch(fetchRequest)

if let maxId = ((results.first as AnyObject).value(forKey: expressionDatMeetiongId)) as? Int {
print("maxId = \(maxId)")
return maxId + 1
} else{
return 1
catch let error {

If you have any requests or questions about the site, please ask from facebook. facebook page