Swift generics to lighten your code

Context

I'm currently designing a Custom NSTextView for an OSX app development. In this scenario I frequently need to access the layoutManager and textContainer of the NSTextView and ended up with many functions like so:


func selectedRect() -> NSRect? {
  if let layoutManager = layoutManager {
    if let textContainer = textContainer {
      return layoutManager.boundingRectForGlyphRange(charRange(), inTextContainer: textContainer)
    }
  }
  return nil;
}

func selectedGlyph() -> NSGlyph? {
  if let layoutManager = layoutManager {
    if let textContainer = textContainer {
      return layoutManager.glyphAtIndex(layoutManager.glyphIndexForCharacterAtIndex(charRange().location))
    }
  }
  return nil
}

... etc ...

Generics

So I decided to refactor the code with the use of generics:


func withLayoutManagerAndTextContainer<T>(callback: (layout: NSLayoutManager, text: NSTextContainer) -> T ) -> T? {
  if let layoutManager = layoutManager {
    if let textContainer = textContainer {
      return callback(layout: layoutManager, text: textContainer)
    }
  }
  return nil
}

Result


func selectedRect() -> NSRect? {
  return withLayoutManagerAndTextContainer { [unowned self] layout, text in
    layout.boundingRectForGlyphRange(self.charRange(), inTextContainer: text)
  }
}

func selectedGlyph() -> NSGlyph? {
  return withLayoutManagerAndTextContainer { [unowned self] layout, text in
    layout.glyphAtIndex(layout.glyphIndexForCharacterAtIndex(self.charRange().location))
  }
}

Of course this is a particular example but you may adapt this to other requirements, you just get the picture