Ham Dong Kyun Ham Dong Kyun - 1 year ago 154
Swift Question

Ambiguous use of 'fetch' error

I am using SWIFT 3.0 on Xcode 8.0
I am trying to loop through the fetched results that was created through template.

let request = model.fetchRequestTemplate(forName: "template")

do {
let result = try context.fetch(request!) // Error on this line
for item: EntityClassName in result! {
} catch {

I get the error "Ambiguous use of 'fetch'". Is my approach wrong? If so what is the right way to loop through the fetched results?

Answer Source

The method fetch you are using returns [Any], because it could be [Dictionary] or [NSManagedObject] or one of its subclasses.

You have to cast [Any] to the proper type

let result = try context.fetch(request!) as! [EntityClassName]
for item in result {

The forced unwrapping is absolutely safe because according to the fetch request it returns always [EntityClassName].

Swift 3 reveals a lot of mistakes made but tolerated in Swift 2 to improve the type safety.

Alternatively you could use the new API with generics, this avoids some type casting.