Skip to content
Ben Guo edited this page Jun 19, 2015 · 1 revision

(WWDC15-411)

Compatibility checking

  • Always use the Latest SDK
  • Toggle deployment target back to earliest release
  • Need to check absence of:
    • frameworks (mark as optional if unavailable on earlier OS)
    • classes/method
      • what if the class/method is private/pre-release?
    • enums (stuck with doing a manual OS version check)
  • In Swift:
    • compiler emits error if API is unsafely used
    • with modules, optional linking is automatic
    • unified syntax for compatibility checks
      • #available(iOS 8.0. *)
      • compiler generates runtime check, infers min OS version
  • Use guard to bail out early
    • guard #available(iOS 9.0, OSX 10.11, *) else { return }
  • Use @available(iOS 8.0, *) to annotate methods

Use nested type enums instead of string constants

  • Strongly-typed > Stringly-typed
  • Centrally located constants
  • Doesn't pollute global namespace
  • Compiler enforces uniqueness of enum cases
  • Allows APIs to be non-failable
extension UIImage {
  enum AssetIdentifier: String {
    case Isabella = "Isabella"
    case William = "William"
  }
  
  convenience init(assetIdentifier: AssetIdentifier) { ... }
}

let image = UIImage(assetIdentifier: .Isabella)

Constrained protocol extensions

protocol SegueHandlerType {
  typealias SegueIdentifier: RawRepresentable
}

extension SegueHandlerType where Self: UIViewController, 
  SegueIdentifier.RawValue == String {

  func performSegueWithIdentifier(...){...}
}

class BrowserViewController: UIViewController, SegueHandlerType {
  // satisfies typealias constraint of protocol
  enum SegueIdentifier: String { 
    ...
  }
}