Skip to content
Pablo Villar edited this page Sep 28, 2016 · 1 revision

In many ways, coding in Swift can be extremely flexible. You can just use it as if it were an alien variant of Objective-C -- with a few gotchas. This is most likely the best way to get the basics of the language under your fingers.

Swift and Objective-C

Interesting links

Coding Strategies

1. Aspirational

Oy, we're talking functional programming. Let's revisit this once the whole team comes up to speed. Specific built-in functions like map and reduce will be discussed in this document now, however.

2. Ideal

Especially for Models, structs are preferable to classes. Structs tend to have much greater performance over classes. Classes with no superclass are preferable to classes subclassed from NSObject, and are therefore preferable, when appropriate. Items that require infrastructure like KVO and Notifications need to subclass from NSObject. Any item that requires UIKit should also be based on NSObject (such as UIViewController, UITableViewDataSource, UIView ...)

The rational behind this is that one's objects should be as lightweight as possible. Structs are value types. Classes are reference types.

Structs will never magically have their underlying data changed from beneath you. Structs will never have threading issues. Structs are your friends. Classes are those friends who you're never sure if they will stab you in the back one day.

A model stores things. In the ideal world, a model is a value type. Controllers and View Models do things, and as such should be Classes.

If your item hierarchy depends on subclassing, use Classes. Structs cannot have any superclass.

Structs vs. Classes

Structs are value types and Classes are reference types.

  • Value types (Structs and Enums) are inherently thread-safe, since they are always passed by value, so the underlying properties will not be changed by a process on another thread.
  • Structs should be considered immutable (although you can mutate their properties via the mutating keyword).
  • Classes are inheritable (a class can have a superclass. A struct cannot).
  • Both Classes and Structs, however, can conform to Protocols.
  • If you need to rely on KVO or respond to NSNotifications, you must use a Class and inherit from NSObject.
  • In the short term, classes are easier to deal with for model objects, especially when passing an item between, say, a UITableViewRow to a detail view. However, keep in mind that this specific example is really hiding a bigger issue, which is one's strategy regarding Maintaining State in an application.

3. Pragmatic

When porting code or in a pinch, use Classes. But realize you should feel guilty for doing so by default, and be ready to back up your design decision with solid reasoning should the inevitable question comes up about it in your pull request.