title: NSTokenField with suggested tokens using Swift
body: <p>I'm new to Swift and am coming from from AppleScript Obj-C. I've read through a few books and am getting comfortable with the syntax, but I still feel pretty lost.</p>
  
  <p>I'm trying to create a simple Token Field that suggests autocomplete tokens like Apple Mail does when it recognizes an email in your contacts. My inspiration comes from <a href="http://macscripter.net/viewtopic.php?id=35197" rel="nofollow">this ASOC script (post #6)</a>. I tried to duplicate it in swift as best I could (without the action menu on tokens):</p>
  
  <pre><code>import Cocoa
  
  @NSApplicationMain
  class AppDelegate: NSObject, NSApplicationDelegate {
  
  @IBOutlet weak var window: NSWindow!
  @IBOutlet weak var tokenField: NSTokenField!
  var theNames = [String]()
  
  
  func applicationDidFinishLaunching(aNotification: NSNotification) {
      tokenField.setDelegate(tokenField.delegate())
      theNames = ["Pomona", "Potomac", "Potable", "Process", "Plow"]
  }
  
  func tokenField(tokenField : NSTokenField, completionsForSubstring substring : String, indexOfSelectedItem selectedIndex : UnsafeMutablePointer&lt;Int&gt;) -&gt; [AnyObject]? {
      var thePredicate = NSPredicate(format: "SELF beginswith[cd] %@", substring)
      var matchingNames = (theNames as NSArray).filteredArrayUsingPredicate(thePredicate)
      return matchingNames as Array
  }
  
  func tokenField(tokenField : NSTokenField, hasMenuForRepresentedObject representedObject : AnyObject) -&gt; Bool {
      return true
  }
  
  
  func applicationWillTerminate(aNotification: NSNotification) {
      // Insert code here to tear down your application
  }
  
  
  }
  </code></pre>
  
  <p>So to sum up. As the user types, if the first letter is "p", a menu with "Pomona", "Potomac", "Potable", "Process", "Plow" should pop up below the word. I'm not sure why nothing is popping up.</p>
  
  <p>Any ideas?</p>
  
  <hr>
  
  <p>EDIT:</p>
  
  <p>Feb 13 2016</p>
  
  <p>Below ioquatix provided the answer to my question but it is beyond my current knowledge level. He did point out a key flaw in my original code is the lack of <code>NSTokenFieldCellDelegate</code> and <code>NSTokenFieldDelegate</code>. Thanks to his help my (simple but limited) solution is:</p>
  
  <pre><code>import Cocoa
  @NSApplicationMain 
  class AppDelegate: NSObject, NSApplicationDelegate, NSTokenFieldCellDelegate, NSTokenFieldDelegate {
  
      var names = ["Pat", "Pot"]
      @IBOutlet weak var tokenField: NSTokenField!
  
      func tokenField(tokenField: NSTokenField, completionsForSubstring substring: String, indexOfToken tokenIndex: Int, indexOfSelectedItem selectedIndex: UnsafeMutablePointer&lt;Int&gt;) -&gt; [AnyObject]? {
          return (names as NSArray).filteredArrayUsingPredicate(NSPredicate(format: "SELF beginswith[cd] %@", substring))
      }
  
  }
  </code></pre>