Monday, April 11, 2016

Overview

This is an interesting addition to the Swift 2.0 language. It acts like a finally for your methods and can be placed anywhere. It is the statement you use when you want to clean up resources. You can learn more about it by reading this nshisper post.

Content

Here’s the scenario. You want to open a file and write some text to it then close it. In Swift 1.0, you would do the following:

1
2
3
4
5
6
7
8
9
10
func writeStatus() {
  let file = openFile()
  
  let networkStatusOptional = fetchNetworkStatus()
  if let networkStatus = networkStatusOptional {
    file.write(networkStatus)
  }

  closeFile(file)
}

This works fine, except if there’s an exception. Another thing that’s bad about this snippet is that the method could be very long (if you’ve read Clean Code, you won’t have this problem) and you have to place the closeFile call at the end.

Here is the Swift 2.0 approach:

1
2
3
4
5
6
7
8
func writeStatus() {
  let file = openFile()
  defer { closeFile(file) }
  
  let networkStatusOptional = fetchNetworkStatus()
  guard networkStatus != nil else { return }
  file.write(networkStatus)
}

The code is cleaner, easier to understand and there is no pyramid of doom. If you haven’t already, you should read my post on the guard statement.

Order of operations

1
2
3
4
5
6
7
8
9
10
11
func firstCall() {
  print("1")
  secondCall()
  print("5")
}

func secondCall() {
  print("2")
  defer { print("3") }
  print("4")
}

The order of the print statements will be 1 2 4 3 5. The defer statement is called right before the method exits even though it’s not the last line in the method.


Random Posts