sloeberGJ sloeberGJ - 4 months ago 18
Swift Question

Is there a way to get string array from array of NSManagedObject for specific attributes

The title may be vague, but I hope my code can clarify a lot. I didn't know what a good title for this question. I'm open to suggestions :D

var resultsOfFetch = [AnyObject]()
if fetchRequest != nil && (textField.text!.characters.count > 4){
do{
let results = try privateMOC.executeFetchRequest(fetchRequest!)
if results.count > 0{
resultsOfFetch = results
}
}catch let error as NSError {
print("Error: \(error) " +
"description \(error.description)")
}
}

var itemNamesArray = [String]()
switch textField{
case self.stampNameField:
for result in resultsOfFetch as! [Stamp]{
itemNamesArray.append(result.itemName)
}


I'm trying to save the itemName of all the returned fetch items in an
array
. Is there a better way to do this? I don't want to be iterating every item in the result array and then taking its item name and then adding it to the itemNamesArray, because it takes time and is very inefficient. Is there a faster way?

Answer

You can use map closure for that

itemNamesArray = (resultsOfFetch as! [Stamp]).map {$0.itemName}