Today I Learned

A Hashrocket project

5 posts about #swift

Use + as a closure in Array reduce

In swift you can pass a method as the closure:

import Foundation

let numbers = [1, 2, 3, 4, 5]
let total = numbers.reduce(0, +)
print("Average: \(total / numbers.count)")

=> "Average: 3"

You can also use the generic closure:

import Foundation

let numbers = [1, 2, 3, 4, 5]
let total = numbers.reduce(0, { accumulator, number in 
  accumulator + number
})
print("Average: \(total / numbers.count)")

=> "Average: 3"

Control video playback with keyboard controls

For a macOS app to show up in the Now Playing media center (which enables media keys [F7, F8, F9]) you just need to configure the MPNowPlayingInfoCenter’s playbackState

func play() {
  self.player.play()
  MPNowPlayingInfoCenter.default().playbackState = .playing
}

And then subscribe to RemoteCommand changes:

let commandCenter = MPRemoteCommandCenter.shared()
commandCenter.pauseCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in
  self.player.pause()
  MPNowPlayingInfoCenter.default().playbackState = .paused
  return .success
}
commandCenter.playCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in
  self.player.play()
  MPNowPlayingInfoCenter.default().playbackState = .playing
  return .success
}
Screen Shot 2021-12-26 at 12 05 47

The Case of the Default 🕵

In Apple’s Swift language switch statements must be what apple calls “exhaustive”. I’ve felt the term to be very literal. Literally exhaustive?

Example that does not work:

let count = 42

switch count {
case 1:
  print(1)
case 7:
  print(7)
}

The above statement does not work because it’s missing a default case. Why? What if I don’t want to do anything else? Why do I need to write something that won’t be used? Don’t worry, there is an amazing and less “exhaustive” way to handle these situations; simply default: ()

Correct example:

let count = 42

switch count {
case 1:
  print(1)
case 7:
  print(7)
default: ()
}