Home > other >  print the 3rd item in a array
print the 3rd item in a array

Time:04-22

In my swift code I am attempting I would like to print the 3rd item in the array that was fetched from core data attribute atBATS. There is a sort descriptor in the code as well. Right now the code prints all the names just print the 3rd name. Assume that the array has 3 items in it.

 func printStrings() {
        let appD = UIApplication.shared.delegate as! AppDelegate

        let context = appD.persistentContainer.viewContext

        let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Data")
        request.returnsObjectsAsFaults = false


        do {
            let result = try context.fetch(request)



            var retrievedData = [String]()

            for data in result as! [NSManagedObject] {
                
                let sort = NSSortDescriptor(key: "atBATS", ascending: false)
                 request.sortDescriptors = [sort]
                
                
                if let value = data.value(forKey: "atBATS") as? String {
                    retrievedData.append((value))


                }

            }


            print(retrievedData)


        } catch {

            print("Failed")
        }
    }

CodePudding user response:

First of all do not name a custom struct or class Data. It can interfere with Foundation Data.

The sort descriptor is at the wrong place. It must be attached to the fetch request before fetching the data.

And you code is outdated. Use always the subclass of NSManagedObject. In the code below I name the class MyData

func printStrings() {
    let appD = UIApplication.shared.delegate as! AppDelegate

    let context = appD.persistentContainer.viewContext

    let request : NSFetchRequest<MyData> = MyData.fetchRequest()
    request.sortDescriptors = [NSSortDescriptor(key: "atBATS", ascending: false)]

    do {
        let result = try context.fetch(request)
        let atBATS = result.map(\.atBATS)
        if atBATS.count > 2 {
            print(atBATS[2])
        } else {
            print("There are less than 3 items")
        }

    } catch {
        print(error)
    }
}
  • Related