5

Is there a more efficient way to retrieve all the names/titles of attributes of a NSManagedObject than this:

func getAllAttributeTitles(_ myStatSheet:StatSheet) -> Array<String> {

    let dictAttributes = myStatSheet.entity.attributesByName
    var arrAttributeTitles:Array<String> = []

    for (key, _) in dictAttributes {
        arrAttributeTitles.append(key)
    }

    return arrAttributeTitles
}
2
  • That’s literally the intended way to do it. Are you finding that it’s inefficient in some way? Slow? Commented Mar 24, 2018 at 16:44
  • No, just wasn't sure if there was a different way to do it that I might of missed. I had to sleuth through the docs to figure it out so just wanted to check. Thanks for the comment. Commented Mar 24, 2018 at 18:33

1 Answer 1

5

As I mentioned, what you've got is the right way to do it. There are other ways but I wasn't at a Mac earlier and couldn't try them out.

A more "Swift-y" way to get the array would be something like

let arrAttributeTitles = myStatSheet.entity.attributesByName.enumerated().map { $0.element.key }

This won't be any more efficient, since it's really doing the same things, but it might be more what you were thinking of when you asked. It's still getting attributesByName and iterating over the result to get strings naming the attributes.

It might be worth noting that the argument type on your method could be NSManagedObject instead of StatSheet, since the code will work for any managed object of any entity type.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, that's really what I was asking, the reduction of lines of code.
Which code would you prefer in your code base, the more Swifty or the more verbose?
If I was writing it I’d write the Swifty version. If someone else on the project wrote your version I wouldn’t think it needed changing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.