Skip to content →

Category: Swift Language

Text Field Advancing Protocol

In Keyboard Responsive View Controller, I discussed a demo project that presented a UIViewController extension for automatically moving the active text field into view when obscured by the keyboard. Not discussed there was functionality included in that project for advancing the cursor to the next text field when the user taps the Return key. I discuss it now.

By default, when the user taps the Return key on the iOS keyboard (in this project configured as a Next or Done button), nothing happens. By conforming your UIViewController to the TextFieldAdvancing protocol, your controller gains a text field auto-advance functionality. As a result, when the user taps Return, the focus automatically moves to the next field in the sequence. Optionally, if it’s the last field on the view, it will instead segue to a new scene.

This protocol does require your controller be registered as a delegate of each text field, which is easiest done via the storyboard. Just control-drag from the text field to the view controller button at the top of the scene, and select the “delegate” outlet. You can also do this programmatically with myTextField.delegate = self (this functionality is included in the Keyboard Responsive View Controller extension).

@objc protocol TextFieldAdvancing: UITextFieldDelegate {
  var textFieldSegueIdentifier: String? { get }
}

extension UIViewController {

  /// In response to the user tapping the Return key in a text field, calls upon `advanceFirstResponder(from:)`.
  func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    advanceFirstResponder(from: textField)
    return true
  }

  /// Advances first responder to the next text field in the `tag` sequence. For the last text field in the sequence, advances to the next scene via the segue given by `textFieldSegueIdentifier`.
  func advanceFirstResponder(from textField: UITextField) {
    guard let vc = self as? TextFieldAdvancing else { return }
    if let nextTextField = view.viewWithTag(textField.tag + 1) {
      nextTextField.becomeFirstResponder()
    } else {
      if let textFieldSegueIdentifier = vc.textFieldSegueIdentifier {
        performSegue(withIdentifier: textFieldSegueIdentifier, sender: nil)
      }
    }
  }
}

The @objc designation on line 1 is required in order for the Swift protocol’s UITextFieldDelegate method textFieldShouldReturn(_:) to be seen and called by the Objective-C UITextField. Without that, tapping Return has no effect.

Turning to the extension, in a perfect Swift world, this would be a protocol extension, with line 5 reading:

extension TextFieldAdvancing where Self: UIViewController {

However, the UITextFieldDelegate calls are similarly never made.  While it runs, the compiler warns:

Non-@objc method textFieldShouldReturn does not satisfy optional requirement of @objc protocol UITextFieldDelegate.

Matthew Seaman provides a good discussion of this problem, summing up the issue so:

@objc functions may not currently be in protocol extensions. You could create a base class instead, though that’s not an ideal solution.

No, not ideal. Using a base class effectively eliminates the utility of using a protocol in the first place. And because we can’t designate that this extension is of TextFieldAdvancing, we must explicitly test for conformance on line 15.

Let that not detract from the fact, however, that this protocol and extension do work. If you want the user to be able to advance automatically through text fields managed by your view controller, simply conform to TextFieldAdvancing, like so:

class MyViewController: UIViewController, TextFieldAdvancing {
  var textFieldSegueIdentifier: String? = "mySegue"
}

And don’t forget to assign the controller as the delegate of each text field!

Leave a Comment

Keyboard Responsive View Controller

keyboardresponsivedemoHere’s a quick-n-easy UIViewController extension that will make any view with UITextFields on it responsive to the keyboard, moving text fields into view when they would otherwise be obscured by it…without requiring scroll views or other storyboard configurations.

I put this together after implementing the Apple approach using scroll views: Moving Content that is Located Under the Keyboard. I found the overhead associated with reconfiguring my existing project views with scroll views significant and the results inconsistent between views. This approach requires no changes to existing views, and needs but one line of code in your controller to enable the feature (plus a couple “optional” ones).

You will find the Swift 3 demo extension project on GitHub in the extension branch (there’s another branch we’ll get to momentarily).

Note, in the real world you’d do better to implement this particular layout in a UITableViewController; I use it here simply for demonstration purposes. This technique is intended more for content that doesn’t lend itself to a tabular or scrolling view. (Also, for simplicity, I forego the universal layout machinations; this one will look decent on an iPhone 6/7 or 6/7 Plus.)

Here’s the extension.

extension UIViewController {

  /// Returns the text field currently identified as the view's first responder, or `nil` if there is no such first responder.
  func activeTextField(within view: UIView?) -> UITextField? {
    guard let view = view else { return nil }
    if view.isFirstResponder {
      return view as? UITextField
    }
    for view in view.subviews {
      if let activeTextField = activeTextField(within: view) {
        return activeTextField
      }
    }
    return nil
  }


  /// In response to keyboard presentation, animates the active text field into view if obscured by the keyboard.
  func keyboardWillShow(_ notification: NSNotification) {

    // The distance between the bottom of the text field and the top of the keyboard
    let gap: CGFloat = 20

    if let activeTextField = activeTextField(within: view),
      let keyboardFrame = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {

      // Calculate delta between upper boundary of keyboard and lower boundary of text field
      let textFieldFrame = activeTextField.superview!.convert(activeTextField.frame, to: view)
      let textFieldBound = textFieldFrame.origin.y + textFieldFrame.size.height + gap
      let keyboardBound = keyboardFrame.origin.y
      let viewShift = min(keyboardBound - textFieldBound, 0) // Don't shift if keyboard doesn't cross text field boundary

      // Shift the view
      var viewFrame = view.frame
      viewFrame.origin.y += viewShift - viewFrame.origin.y // Account for previous shift
      UIView.animate(withDuration: 0.5) {
        self.view.frame = viewFrame
      }
    }
  }

  /// In response to keyboard dismissal, animates the view back to its original position.
  func keyboardWillHide(_ notification: NSNotification) {
    var vwFrame = view.frame
    vwFrame.origin.y = 0
    UIView.animate(withDuration: 0.5) {
      self.view.frame = vwFrame
    }
  }

  /// Enables keyboard responsiveness to text fields, animating the view such that the currently active text field is not obscured by the keyboard. Call this method from `viewDidAppear(_:)`.
  func activateKeyboardResponsiveTextFields() {
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
  }

  /// Disables keyboard responsiveness to text fields. Call this method from `viewWillDisappear()`.
  func deactivateKeyboardResponsiveTextFields() {
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
  }
}

The view controllers you wish to take advantage of this behavior need to call upon those last two methods, as follows:

override func viewDidAppear(_ animated: Bool) {
  activateKeyboardResponsiveTextFields()
}

override func viewWillDisappear(_ animated: Bool) {
  view.endEditing(true)
  deactivateKeyboardResponsiveTextFields()
}

The call to endEditing() on line 6 is not strictly necessary, but I found overcame some less-than-premium keyboard presentation behavior when unwinding to a controller that had previously segued with the keyboard visible.

Note that in the extension itself, beginning on line 4, we cannot obtain the activeTextField the same way Apple does in their example code, that is, by using the UITextFieldDelegate methods textFieldDidBeginEditing(_:) and textFieldDidEndEditing(_:). This is because they use a stored property to capture the active field. Thus the extension must find it programmatically by recursively traversing the view’s subviews, looking for the one that isFirstResponder.

This activeTextField(within:) method is called once each time the keyboard shows, which actually happens each time a field becomes the first responder, such as when the focus moves from one text field to the next, even if the keyboard is already present. This process happens so quickly within the run loop, however (even with this activeTextField(within:) traversal), that the keyboard doesn’t actually dismiss and reappear.

Where could you go from here?

While this extension is arguably Swifty and lightweight, there is some overhead we carry into each view controller taking advantage of it. We can eliminate that overhead by converting the extension into a subclass of UIViewController. While perhaps non-Swifty (classes are so heavyyy), it does have these benefits:

  • Replaces what amounts to a computed activeTextField property with a stored property (however negligible that processing requirement may be).
  • Eliminates the explicit calls to (de) activateKeyboardResponsiveTextFields(). Instead, one must only subclass KeyboardResponsiveViewController.

Take a look at the subclass branch of the repo for this implementation.

Leave a Comment

extension Queue: SequenceType

Previously, I presented a linked-list-based Queue class in the context of a discussion around Automatic Reference Counting (ARC). Here I extend that class to conform to the SequenceType protocol, and then add some bonus initializers that mirror those given for Swift’s collections.

In simplest terms, it is the SequenceType protocol that allows us to iterate over the elements in the Queue:

for element in queue {
  // do something with element
}

But that’s just the beginning. Taking a look at the Appe documentation and this excellent post by Nate Cook on the Swift Collection Protocols, we find that because of this iterability, we gain significant functionality for free, a subset of which includes the likes of enumerate, map–filter–reduce, reverse, sort, and so on. Good stuff!

Now, a SequenceType makes no guarantees as to whether the sequence is consumed, so if we were interested only in iteration and didn’t care about that (or perhaps wanted it to be consumed), we could destructively iterate like so:

while let element = queue.dequeue() {
  // do something with element
}

However, our Queue is constructed in such a way that it need not be consumed on iteration.

Generator

So let’s give Queue an iterator (generator in Swift vernacular) and declare its conformance to the SequenceType protocol. There’s not much to it, at least as far as Queue is concerned:

extension Queue: SequenceType {

  /**
   Returns a `SequenceType` generator for iterating over the queue.
   */
  func generate() -> QueueGenerator<T> {
    return QueueGenerator(queue: self)
  }
}

Beyond that, we need only define the QueueGenerator returned by generate(). It takes our Queue object and, with its front property and each node’s next property, non-destructively iterates over the elements in the queue:

/**
 The generator by which `Queue` conforms to `SequenceType`.
 */
struct QueueGenerator<T>: GeneratorType {
  
  /// The queue being iterated over.
  var queue: Queue<T>
  
  /// The current node.
  var node: QueueNode<T>?
  
  /**
   Initializes iteration at the front of the given `queue`.
   */
  init(queue: Queue<T>) {
    self.queue = queue
    node = queue.front
  }
  
  /**
   Returns the next element in the queue, or `nil` if the queue is empty or all nodes have been iterated.
   */
  mutating func next() -> T? {
    let element = node?.element
    node = node?.next
    return element
  }
}

Notice that like the previously defined dequeue() method, the next() method is not returning a queue node, but rather the element of type T that is wrapped by the node.

And that’s all there is to for SequenceType conformance!

Initializers

But before we move on, let’s go back to our original Queue definition and drop in some initializers that allow Queue construction to work like Swift’s own Array and Set types:

class Queue<T>: SequenceType, ArrayLiteralConvertible { // continued

  /**
   Construct an empty queue.
   */
  init() { }
  
  /**
   Construct an instance containing `elements`.
   */
  required init(arrayLiteral elements: T...) {
    for element in elements {
      enqueue(element)
    }
  }
  
  /**
   Construct an instance from an arbitrary sequence with elements of type `Element`.
   */
  init<S: SequenceType where S.Generator.Element == T>(_ sequence: S) {
    for element in sequence {
      enqueue(element)
    }
  }
}

The first constructor was implied by the previous omission of any initializers, but now that we’ve added the other two, we must explicitly define it. However, because Queue consists only of optional properties, they are automatically initialized to nil. Since this is the “default” state, there is nothing for it to initialize.

The second initializer uses the Swift ellipses syntax to indicate a comma-separated list of literal values, which it converts into an Array. This is all that’s needed for ArrayLiteralConvertible protocol conformance, so I add that to the class. This in turn necessitates the use of the required modifier on the initializer, as the initializer is required by the protocol.

Finally, the third initializer allows us to build a queue from any SequenceType, such as an Array, Set or Dictionary. The syntax used here is that of the generic parameter clause, which adds a constraint to the Queue‘s generic argument T. That constraint says S conforms to the SequenceType protocol and the associated type S.Generator.Element is of type T. In other words, we can pass in any sequence of type T elements.

Here’s what those initializers look like in application.

let array = [3, 7, 2, 9]
let set = Set(arrayLiteral: 3, 7, 2, 9)
let dict = ["A": 3, "B": 7, "C": 2, "D": 9]
let queue1 = Queue<Int>()
let queue2 = Queue(arrayLiteral: 3, 7, 2, 9)
let queue3 = Queue(array)
let queue4 = Queue(set)
let queue5 = Queue(dict.values)
let queue6 = Queue(queue2)

Some points of note:

  • We’re able to drop the <Int> type specification on any but the first initializer, thanks to Swift’s type inference.
  • We can now initialize one Queue with another.
  • Only the Queue and Array types maintain their order as initialized, so the arrangement of the elements for queue4 and queue5 are not necessarily 3, 7, 2 and 9.
Leave a Comment

A Generic Swift Queue and ARC

In my current project, I set off to implement a generic queue in Swift, and settled on the use of a linked list for doing so, where my queue is a collection of singly linked nodes. As it turned out, this ended up being fertile ground for illustrating Swift’s use of Automatic Reference Counting (ARC) for memory management, something I take on in this post.

For the visual learners, here is an illustration to assist the discussion, courtesy of Paper by 53 and my iPad Pro (with Apple Pencil, of course):

IMG_0040

The top row represents three people waiting in line at Walmart customer service (who hasn’t been there?). The second row shows the first person has been helped (dequeued), leaving two. And the third row shows two new customers have arrived (enqueued), eager to make their returns, before anyone else has been helped. The orange numbers correspond to reference counts (more on that in a moment).

Queue Node

So to begin, let’s take a look at the building block of the queue, the node (represented by the circles in the diagram):

/**
 The component of a queue that provides the queue's content and sequence.
 */
class QueueNode<T> {

  /// The data element stored in the queue.
  var element: T

  /// The node that is "next in line", or `nil` if there is no subsequent node.
  var next: QueueNode?

  /**
   Wraps the given `element` into a node, leaving `next` set to `nil`.
   */
  init(element: T) {
    self.element = element
  }
}

Being part of a linked list, it is necessary for the node to be a class, as linked lists rely on reference pointers, and only Swift classes—as reference types—can be “pointed” to. (In contrast, any assignment of a structure or enumeration stores a copy of the object in the receiving variable, property, or parameter.)

Queue

Next, let’s begin taking a look at the class that takes the QueueNode building block and with it forms a fully functional Queue data structure:

/**
 A generic collection that provides standard enqueueing and dequeuing functionality.
 As elements are enqueued, they are conceptually added to "the back of the line;" 
 as they are dequeued, they are removed from "the front of the line." 
 */
class Queue<T> {

  /// The first enqueued node or that following the last dequeued node.
  private var front: QueueNode<T>?

  /// The last enqueued node.
  private var back: QueueNode<T>?

  /// The number of elements in the queue.
  private(set) var count = 0
  
  /// True if there are no elements in the queue, false otherwise.
  var isEmpty: Bool {
    return count == 0
  }
 

I want to interrupt here to point out that the class properties front and back defined on lines 9 and 12 are effectively pointers, as is the function variable node on line 28 below (reference the diagram).

  /**
   Adds the given `element` to the back of the queue.
    - complexity: O(1)
   */
  func enqueue(element: T) {
    
    let node = QueueNode<T>(element: element)
    
    // First node
    if front == nil {
      front = node
      back = node
    }
      
    // Subsequent nodes
    else {
      back!.next = node
      back = node
    }

    count += 1
  }
 

It is on line 28 that this class allocates memory for, creates, initializes and assigns a reference to a new QueueNode object (all done behind the scenes by Swift). In accordance with ARC, as long as this object has a property, variable or parameter pointing to it, it will remain allocated. This node is short-lived, though, so the only potential direct references held by Queue are front and back. It is the nodes themselves that maintain the next references keeping the chain of nodes alive (again, the diagram).

  /**
   Removes and returns the element at the front of the queue.
   - complexity: O(1)
   */
  func dequeue() -> T? {
     
    // Queue is empty
    if front == nil { return nil }
     
    // Remove first node/element
    let element = front!.element
    front = front!.next
     
    // Deallocate dequeued back node
    if front == nil {
      back = nil
    }
 
    count -= 1
     
    return element
  }
 

Consider line 56 in dequeue(), where front is reassigned to the object pointed to by its own next property. This leaves the node formerly known as first with nothing referring to it, triggering implicit and immediate deallocation; there’s no need to explicitly deallocate it, such as with a nil assignment.

In contrast, if we have dequeued the last node, we need to explicitly release it by reassigning back to nil (line 60), otherwise back will retain that node until the queue itself is deallocated (at which time it is automatically set to nil).

Automatic Queue Deallocation

In the context of queue deallocation, such as when the reference count for a Queue object drops to zero, front is assigned to nil. When that happens the associated node’s reference count also drops to zero, triggering its deallocation. This causes the setting of the node’s next property to nil, which then decrements its adjacent node’s reference count to zero, thereby triggering that node’s deallocation, and so on. This chain reaction continues until the last node in the linked list is reached.

As discussed in the context of dequeue(), this last node is also pointed to by the queue’s back property, thus preventing its reference count from dropping to zero, and thereby keeping the object alive. It is not until back is set to nil (line 60 above) that the reference count drops to zero and the last node is deallocated.

The process of deallocating the nodes between front and back happens automatically courtesy of ARC memory management built into Swift and Objective-C. You can see it in action by using this script and addition to QueueNode:

class QueueNode<T> { // continued
  deinit {
    print("\(#function)")
  }
}

func testQueue {
  let n = 10
  var queue = Queue<Int>()
  for i in 1...n {
    queue.enqueue(i)
  }
}
testQueue()
print("done")

Once testQueue() exits, you’ll see its queue variable is automatically deallocated as described, which in this case would result in 10 debugger console output lines that read “deinit” before “done” appears.

Large Queues

Now you might find that for large queues, trouble ensues in the form of a EXC_BAD_ACCESS runtime error. I found taking the reigns on deallocating the individual QueueNodes ensured the deallocation of any sized queue works flawlessly.

Returning to our Queue definition, this is a simple matter of adding a deinit method that calls upon a removeAll() method familiar to users of Swift’s collection types:

  /**
   Explicitly deinitializes all enqueued nodes.
   - complexity: O(n)
   */
  deinit {
    removeAll()
  }

  /**
   Removes all elements from the queue.
   - complexity: O(n)
   */
  func removeAll() {
    while front != nil {
      front = front!.next
    }
    back = nil
    count = 0
  }
}

Note we haven’t completely given up on ARC. As it did in line 56 previously, the same implicit deallocation occurs here on line 82: as soon as the front = front!.next assignment is made, the node that was the front node is deallocated. Where we short-circuit the automatic chain-reaction deallocation discussed above is in that front reassignment. Were we to replace lines 81–83 with a simple front = nil, we would be back to the default behavior we had without a deinit method.

And yes, for you lines-of-code hounds out there, I could have written removeAll() as a simple one-liner with the loop while dequeue() != nil { }. I contend, though, the given approach is superior for performance reasons, however negligible. There’s a bit more overhead in calling dequeue() 100 million times, let’s say, than in dereferencing that many nodes directly (in a single test, this amounted to 45 versus 65 seconds…a near 150% increase).

More to Come

That does it for now. In my next post I conform the Queue to SequenceType so it can be iterated with the likes of:

for element in queue {
  // do something with element
}
Leave a Comment

RIP++

When I recently had occasion to “prepare” for Swift 3.0 a third-party library our team is using, it struck me just how useful the C-based post-increment (and decrement) operator is. Consider this simple Swift 2.2 line from that library:

return (String(self.arrayIndex++), JSON(o))

To those not familiar with this post-increment unary operator, the arrayIndex doesn’t get incremented until after it is converted to a String. With the loss of that operator in Swift 3.0, this one-liner grows to this:

let arrayIndexString = String(self.arrayIndex)
self.arrayIndex += 1
return (arrayIndexString, JSON(o))

Can’t say I agree with the stated “disadvantages” of this operator, which appear to focus on a very simplistic use-case that contrasts x += 1 and x++. Sure, in that case, there’s no added utility. And hard to learn? I’ve seen that argument repeated in other “do away with this” arguments; hog wash. Swift contains much more complicated constructs than a post-increment operator!

Alas, I’m a bit late to the party, and the fate of ++ has already been sealed. Thankfully, it’s not “goodbye,” but just “see you later”…when I return to the likes of C++.

Leave a Comment

App State-Change Notifications to Multiple Delegates

In a prior post on Modeling State with Associated Enums, I set up a mechanism for capturing and querying an app’s state, as follows:

AppState.state = .Authentication(.Active)
AppState.state = .DataRetrieval(.Success)
// ...
if AppState.state == .DataRetrieval(.Success) {
  // ...
}

In this post I use the delegate pattern to add state observation by any component of the app that needs to respond to state changes. I begin by defining the delegate protocol:

/**
 An `AppStateDelegate` receives notification when the application's state changes.
 */
protocol AppStateDelegate {

  /// Called when the app state has changed.
  func appStateChanged(state: AppState)

  /// Uniquely identifies the delegate.
  var hashValue: Int { get }
}

The appStateChanged(_:) method will be called any time the state changes (makes sense!). But what about that hashValue on line 11? When it comes to delegates, this is an instance where it is appropriate and, perhaps, necessary to register multiple delegates: there are likely to be multiple places across the app where I need to know about state changes. The hashValue is going to help with that…

My approach for supporting multiple delegates without using NSNotificationCenter is to add to the previously defined AppState enumeration a dictionary of delegates:

enum AppState: Equatable { // excerpt

  /// Delegates registered for `appStateChanged(_:)` notifications.
  private static var delegates = [Int: AppStateDelegate]()
}

(Before getting to the dictionary, note I have chosen to make this and future declarations static. I have done so because, not unreasonably, the state of the app applies to the entire app, and there is only one instance of the app running at a time.)

It is to this AppStateDelegate dictionary that notifications will be made. I have chosen a dictionary here as a meet-me-halfway point between an array and a set. A set would be ideal, but it requires the delegate to conform to the Hashable protocol, something not as easy as it seems, and that I leave for a future exercise. In the meantime, we’ll use the dictionary so as to prevent registration of duplicate delegates.

Delegate registration occurs via the delegate property setter, defined next:

enum AppState: Equatable { // excerpt

  /// Registers the `delegate` with `AppState`.
  /// All delegates are notified upon assignment to `state`. 
  static func addDelegate(delegate: AppStateDelegate) {
    delegates[newValue.hashValue] = newValue
  }
}

The addDelegate(_:) method simply adds the given delegate to the dictionary, relying on the default no-duplicate-keys functionality that comes with a dictionary to ensure no delegate is registered more than once.

A delegate property could be used in lieu of this method, using the setter to make this same dictionary addition, but doing so actually adds a level of unneeded complexity given we’re using multiple delegates: which delegate should the getter return? Using a method avoids that peculiarity.

The dictionary is keyed on the protocol’s hashValue integer. The expectation is any registering delegate itself already conforms to the Hashable protocol (without explicitly requiring such conformance), and thereby has a fitting hashValue implementation that will ensure the uniqueness of the key. If it doesn’t conform, the AppStateDelegate protocol requires a hashValue anyway, so I call it good for now.

With delegates registered, notification is triggered by the following didSet block:

enum AppState: Equatable { // excerpt

  /// The current state of the app. 
  /// Any assigned `AppStateDelegate`s are notified on assignment.
  static var state: AppState = .Ready(false) {
    didSet {
      for delegate in delegates.values {
        delegate.appStateChanged(state)
      }
    }
  }
}

The process of notification is quite simple: call appStateChanged(_:) on each of the delegates in the dictionary. (Note, as explained by the Swift Programming Language Guide, didSet is not called when the value is first initialized.)

Putting all that to use, here is a sample listener implementation that shows registering as a delegate for and receiving app state-change notifications.

import UIKit

class SomeViewController: UIViewController, AppStateDelegate {

  override func viewDidLoad() {
    AppState.delegate = self
  }

  func appStateChanged(state: AppState) {
    if state == .DataRetrieval(.Success) {
      // do something...
    }
  }
}

Note that because a UIViewController already conforms to the Hashable protocol, there is no need to explicitly provide a hashValue implementation. The result? Each time AppState.state is updated, this controller and any other registered delegates are notified via the protocol’s appStateChanged(_:) method.

Leave a Comment

Modeling State with Associated Enums

Shortly after writing a recent post on enums with associated values, I came upon another use case for such: representing transitory app states.

Here is the scenario. I have an app that goes through an authentication process: attempting to authenticate, successfully authenticated, or failed to authenticate. Similarly, upon authentication, it goes through a second series of steps for data retrieval: requesting and receiving the data, data received, or retrieval failed. Finally, book-ending those two processes, the app has a ready state: either it is or it isn’t ready.

Here’s how I represent these states with associated enum values:

enum AppState {

  case Authentication(OperationState)
  case DataRetrieval(OperationState)
  case Ready(bool)

  enum OperationState {
    case Active
    case Success
    case Failure
  }

  static var state: AppState = .Ready(false)
}

First, AppState captures as case statements the two processes for authentication and data retrieval, and the ready state. The associated value for the processes is the nested OperationState enumeration that captures one of the three states of each of those processes: Active, Success, or Failure. The Ready state need only be represented as true or false. It is the static state property on line 13 that allows me to capture any of those mutually exclusive transitory state values for the app.

Now I can establish that app state and test it like so:

AppState.state = .Authentication(.Active)
AppState.state = .DataRetrieval(.Success)

// ...

switch AppState.state {
case .Authentication(let state):
  switch state {
  case .Active:
    break // stand by
  case .Success:
    break // proceed with data retrieval
  case .Failure:
    break // can't retrieve the data
  }
case .DataRetrieval(let state):
  if state == .Success {
    // refresh the table view
  }
case .Ready(let ready):
  if ready { //...
  }
}

There are two types of comparison here: a switch statement and an if statement. Actually, the if statement on line 17 won’t work out of the box. We first need to conform our AppState to the Equatable protocol (if you’re doing this in a playground, it must go above the AppState definition):

func ==(left: AppState, right: AppState) -> Bool {
  switch (left, right) {
  case (.Authentication(let l), .Authentication(let r)): return l == r
  case (.DataRetrieval(let l), .DataRetrieval(let r)): return l == r
  case (.Ready(let l), .Ready(let r)): return l == r
  default: return false
  }
}

enum AppState: Equatable {
  // The external func ==(left:right:) satisfies Equatable
}

The default case is necessary here because we’re not testing every combination of left and right AppStates; with out it, we’d have to be more explicit, adding these cases:

  case (.Ready, .Authentication): return false
  case (.Ready, .DataRetrieval): return false
  case (.Authentication, .Ready): return false
  case (.Authentication, .DataRetrieval): return false
  case (.DataRetrieval, .Ready): return false
  case (.DataRetrieval, .Authentication): return false

In those instances, we’d in effect be comparing apples and oranges, which are not equal; so we return false. And clearly, having a default return value of false in lieu of all those case statements is preferable.

That’s it! In this illustration I employed associated value enums to represent in a very clean, readable way a series of states that various operations of the app can be in.

In a follow-up post I extend this with a delegate pattern for making notifications when the app’s state changes.

Leave a Comment

Nested Enumerations as Dictionary Keys

Type of expression is ambiguous without more context.

This may be an error you have seen before. It apparently occurs in more than one circumstance, this being one example of such:

struct Foo {
  enum Bar {
    case Alpha
    case Beta
  }
}
var outer = [Foo.Bar: String]() // Error

There are three ways I found to get that enum to work as a dictionary key. The first is to use it within the enclosing type:

struct Foo {
  enum Bar {
    case Alpha
    case Beta
  }
  var inner = [Bar: String]()
}

That’s hardly a solution, however, if you need a dictionary outside the context of Foo. What’s more, this usage doesn’t align with the Swift Programming Language Guide‘s statement:

To use a nested type outside of its definition context, prefix its name with the name of the type it is nested within: let heartsSymbol = BlackjackCard.Suit.Hearts.rawValue.

The second workaround is to move the Bar enum outside of Foo:

enum Bar {
  case Alpha
  case Beta
}

var dict = [Bar: String]()

Unfortunately, this forces Bar to lose its Foo context, which is the Guide’s primary stated purpose for having nested types in the first place:

Enumerations are often created to support a specific class or structure’s functionality. Similarly, it can be convenient to define utility classes and structures purely for use within the context of a more complex type. To accomplish this, Swift enables you to define nested types, whereby you nest supporting enumerations, classes, and structures within the definition of the type they support.

The third workaround is less a workaround than a solution, and that is to use the full notation for a dictionary declaration:

struct Foo {
  enum Bar: String {
    case Alpha
    case Beta
  }
}
var outer = Dictionary<Foo.Bar, String>() // Works!

Why the abbreviated syntax leads to an ambiguous type reference remains unclear, but using the full syntax does the trick.

Leave a Comment

Naming Swift Methods

How to name methods in Swift is a fairly common discussion point with my team, and one of repeated frustration for those members new to iOS development. Largely at issue is named parameters: that we use them at all (what is their value?), and how to use them.

To illustrate their value, I present a brief example. Consider this method I wrote that needs to communicate to a delegate when a document object has finished processing an XML representation of a weather layer with a certain name. I named this method as so:

func capabilitiesDocument(document: CapabilitiesDocument, 
  didProcessXMLLayer xmlLayer: XMLElement, 
  withName name: String)

The signature for this method reads:

capabilitiesDocument(_:didProcessXMLLayer:withName:)

I would argue this name communicates very clearly the intent of that method (it’s not unlike the UITableViewDelegate method tableView(_:didSelectRowAtIndexPath:)). In contrast, consider the omission of the external argument names: capabilitiesDocument(_:xmlLayer:name:). Here the method’s purpose is completely lost; named parameters clearly communicate that intent.

Naming methods in this manner may be somewhat of an art; it is not always clear cut. Thankfully, we are not without authoritative guidance.

First, understand Swift has its heritage in the Objective-C community, and Apple has made it clear that Swift adopts the Objective-C style. To this point, the Swift Programming Language Guide states in its discussion on Methods:

Methods in Swift are very similar to their counterparts in Objective-C. As in Objective-C, the name of a method in Swift typically refers to the method’s first parameter using a preposition such as withfor, or by, as seen in the incrementBy(_:) method from the preceding Counter class example. The use of a preposition enables the method to be read as a sentence when it is called.

You don’t need to define an external parameter name for the first argument value, because its purpose is clear from the function name incrementBy(_:numberOfTimes:). The second argument, however, is qualified by an external parameter name to make its purpose clear when the method is called.

The behavior described above means that method definitions in Swift are written with the same grammatical style as Objective-C, and are called in a natural, expressive way.

So there you have it. The goal is a Swift method definition that can be called in a natural, expressive way, as is done with Objective-C.

Given that Apple establishes this link between Swift and Objective-C method naming guidelines, it is reasonable to turn to their Coding Guidelines for Cocoa as an authoritative source for naming not only methods, but also variables, types, delegates, etc. While the guidelines are not 100% applicable to Swift (such as the naming of accessors, which Swift makes implicit), for the most part they are.

Apple does provide some discussion of this in a Swift-specific context in their API Design Guidelines. You will not find any contradictions between this and the Cocoa guidelines, but perhaps some clarifications.

Finally, in the spirit of leading by example, an extremely good source for a practical application of these guidelines are Apple’s framework references, such as the UIKit Framework Reference. These give hundreds upon hundreds of examples of method and property names that follow these conventions.

Happy Swifting!

Leave a Comment

Property Value Observing of Struct Types

The Swift Programming Language Guide has this to say about property value observing:

You have the option to define either or both of these observers on a property:

  • willSet is called just before the value is stored.

  • didSet is called immediately after the new value is stored.

Given that, how many times would you expect the following snippet to produce an output, “didSet dict”?

class SomeClass {
  var dict: [String: String]? {
    didSet {
      print("didSet dict")
    }
  }
}
let myClass = SomeClass()
myClass.dict = [:]
myClass.dict?["A"] = "alpha"
myClass.dict?.removeValueForKey("A")

What the documentation does not make clear is that for structures, which are value types, property observers are triggered both on assignment and on mutation; for classes, which are reference types, they are only triggered on assignment.

So for this example, where dict is a structure, didSet is called three times: once for the initial assignment, and twice for the two mutations. Good to know!

Leave a Comment