Choosing How to Implement Functionality in Swift - dummies

Choosing How to Implement Functionality in Swift

By Jesse Feiler

When you’re thinking about creating an app, how do you decide how to implement its functionality? Swift, along with the Cocoa and Cocoa Touch frameworks, provides a wide variety of tools to assist you. Here’s a list of some of the questions to ask yourself when deciding which one(s) to use:

  • Is this something that people need to be able to do both on iOS and OS X? If the answer is yes, consider building an Xcode workspace with an iOS target and an OS X target along with shared code.

  • Is this something that people need to be able to do on multiple devices? Consider implementing iCloud so that the data can be shared across devices.

  • Will several people work on this project? Use the built-in Git source control mechanism in Xcode.

The answers to the preceding questions should help you understand what you’re building and how you intend to manage the source code. With those decisions made, consider these Swift-specific questions:

  • Is this functionality something that is occurs repeatedly in different contexts with different data or that involves data manipulation and calculations? If so, chances are this should be a function or a class.

    • Classes often contain functions and data (although they may contain one or the other). They tend to be more complex than functions, but note that in Swift, very light-weight functions tend to be used more frequently than in other object-oriented languages.

    • Examples of functions are calculations such as a cost based on base price, markup, and quantity of items, filling user interface elements with data from a data store, managing the transition to or from background.

  • Is this a matter of organizing like data? If so, a collection type such as an array or dictionary may be the answer. Swift can enforce the rules so that you know each element is of a similar type.

  • Is this operation always the same or are there different procedures depending on circumstances (data, external conditions, and so forth)? If so, you might consider the flow control operators such as loops and conditions. (You can use them within functions.)

  • Do you need to provide functionality only to certain types of data? In this case, consider adding functions to a structure, method, or class.