You must point the array of the managed object to the correct type:
for result in results! as [Users] { println(result.username) }
It is assumed that you have created a subclass of the managed object for the Users object.
You should also distinguish whether executeFetchRequest() returned nil (i.e. the query to fetch failed) or 0 (i.e. no objects were found), and use the error parameter:
var error : NSError? if let results = context.executeFetchRequest(request, error: &error) { if (results.count > 0) { for result in results as [Users] { println(result.username) } } else { println("No Users") } } else { println("Fetch failed: \(error)")
Update for Swift 2 / Xcode 7 with try / catch error handling:
do { let results = try context.executeFetchRequest(request) as! [Users] if (results.count > 0) { for result in results { print(result.username) } } else { print("No Users") } } catch let error as NSError { // failure print("Fetch failed: \(error.localizedDescription)") }
Please note that forced as! [Users] as! [Users] is acceptable here. The returned objects are always instances of the corresponding class that were configured in the inspector of the Core Data model, otherwise you are a programming error that must be detected earlier.
source share