Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

print the 3rd item in a array

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")
        }
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading