Reputation:
in my class I have a method to extract data from coredata. But I have a problem: I need to convert the result to an array, because then I'll have to use that array in an other class.
The method is:
func loadQuestion() -> NSArray{
let fetchRequest: NSFetchRequest<Questions> = Questions.fetchRequest()
do {
let array = try self.context.fetch(fetchRequest) as NSArray
guard array.count > 0 else { print("[EHY!] Non ci sono elementi da leggere "); return array }
return array
} catch let errore {
print("error FetchRequest")
}
return list
}
I can't figure out how to convert the variable array?
The result (wrong)
Edit: I write this because I want to convert the result of fetch into an array, so you can switch to another class
Upvotes: 5
Views: 4657
Reputation: 114875
fetch
returns an (optional) array, so all you need to do is return that from your function. Since fetch
throws
your function should either throw
or at least return an optional, as the fetch can fail.
In Swift it is very rarely necessary to use NSArray
; a properly typed Swift array will make your code clearer and safer. Since CoreData in Swift supports Generics, fetch
will return the appropriate array type automatically, based on your NSFetchRequest
. Even if you are calling this function from Objective-C, it is best to let the compiler bridge the Swift array to an NSArray
for you
Finally, you are using guard
incorrectly; you attempt to return array
in the case where it has 0 items, otherwise you return some variable list
which isn't declared in the code you have shown.
func loadQuestion() -> [Questions]? {
let fetchRequest: NSFetchRequest<Questions> = Questions.fetchRequest()
do {
let array = try self.context.fetch(fetchRequest) as [Questions]
return array
} catch let errore {
print("error FetchRequest \(errore)")
}
return nil
}
Upvotes: 4