How to convert the index (optional Int) of the element of a fetch request to Int

`func countingLastOccurrence(filterkey1: String) -> Int {

        let context = PersistenceController.shared.container.viewContext

        let fetchquest1 = NSFetchRequest<Filedetails>(entityName: "Filedetails")

        fetchquest1.sortDescriptors = [NSSortDescriptor(keyPath: \Filedetails.year, ascending: false), NSSortDescriptor(keyPath: \Filedetails.sequence, ascending: false)]

        fetchquest1.predicate = NSPredicate(format: "%K == 1", filterkey1)

        let item1 = try? context.fetch(fetchquest1).firstIndex

       let item1a = item1.compactMap { Int($0) }

        return item1a`

Hello, I would like to ask how to convert the result of the fetchquest which is an optional to an Int ?

Value of type '((Filedetails) -> Array.Index?)?' (aka 'Optional<(Filedetails) -> Optional>') has no member 'compactMap'

I had tried to force unwrapped it :

let item1a = item1 ?? 0

but it show "Binary operator '??' cannot be applied to operands of type '((Filedetails) -> Array.Index?)?' (aka 'Optional<(Filedetails) -> Optional>') and 'Int'"

Thank you so much.

Did you try:

var item1a = 0
if let item1 = try? context.fetch(fetchquest1).firstIndex {
    item1a  = item1 ?? 0
}

Thank you for your reply.

I tried your suggestion, it still had error

  1. Binary operator '??' cannot be applied to operands of type '(Filedetails) -> Array.Index?' (aka '(Filedetails) -> Optional') and 'Int'

  2. No '??' candidates produce the expected contextual result type 'Int'

I don't know why

Look at that error message. You are trying to apply ?? to something of type (Filedetails) -> Array.Index?. That’s not an array index, but rather a function that returns an array index. You are not calling the function and trying to apply ?? on its result, you are trying to apply ?? to the function itself. Once you look at it this way, it’s clear why it won’t work.

As to how you got here, that’s more subtle. The issue is with your use of firstIndex. That’s actually a function call, to the function:

func firstIndex(of element: Self.Element) -> Self.Index?

If you want the index of the first item in the array, use startIndex, so:

let item1: Int? = (try? context.fetch(fetchquest1))?.startIndex

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

How to convert the index (optional Int) of the element of a fetch request to Int
 
 
Q