Earlier we were working on adding some toolbar items to the editor window and wanted to get a toolbar item based on its Identifier String. Looking into the developer documents to find the right function to call, we found… nothing. What’s up with that Apple?
The only way we found we could access the right toolbar item was to use something like this:
For us, that wasn’t really acceptable, there had to be a better way, since there was no guarantee that our item would be the 4th item in the items array (if there were that many items to begin with)
Swift Extensions
Since we have been using Swift to write the this application, we decided to use a very nice Swift feature called extensions. From the online reference at Apple’s developer website:
Extensions add new functionality to an existing class, structure, enumeration, or protocol type. This includes the ability to extend types for which you do not have access to the original source code (known as retroactive modeling). Extensions are similar to categories in Objective-C. (Unlike Objective-C categories, Swift extensions do not have names.)
Very very cool. So off we went and wrote our own. Here’s what we came up with:
Update: We are now using the more concise and better written Version 2 of our code. Thanks to a few people in the chat room we hang out in for pointing out the better implementation Freenode iDevGames Chat Room.
Version 1:
Here’s what it’s doing: The function loops through the items array associated with the toolbar (since this is an instance method ‘self’ is the toolbar we are working on) and checking the item’s Identifier String, if it matches the one that was passed into the function, return it. If we go through all the items and we don’t find one, we return nil (which means unset or empty).
Version 2:
The second version of the code is doing the same thing, but it’s using the built-in array function first to find the first item in the items array what matches our condition. the
$0
in the code is a reference to the item that the first function is referencing at the point in the loop, it checks our condition and if it’s met, then it returns the item, otherwise first returns nil for the result.
And there we have it. We can now get a toolbar item from an identifier string.
That’s all for now!