title: Adopting Objective-C protocol and returning NSArray
body: <p>I have a delegate class coded in Swift. I have an Objective-C class that has a delegate property of this Swift class. The Swift delegate class adopts an Objective-C protocol with a required property of type NSArray*. The Swift code builds a mutable array class var then returns that as [AnyObject]. </p>
  
  <p>The building of the mutable array and the assignment of that to the Swift class var works, but sometimes the function returns nil back to my Objective-C class. </p>
  
  <p>When I set a breakpoint and step through line by line it works, but if I just let it run it returns nil every time. </p>
  
  <p>I have also put in log statements that verify the Swift class builds the mutable array every time but the Objective-C code keeps getting nil. The only thing I have gotten to work is to change my Objective-C protocol property to NSMutableArray but that seem like I am bypassing the problem. How can I make this work using NSArray?</p>
  
  <p>If I make the Swift code return NSArray! I get a compile error saying the Swift class does not implement the required delegate method.</p>
  
  <p>If I change the Swift code to return</p>
  
  <pre><code>Array&lt;AnyObject&gt;
  </code></pre>
  
  <p>it compiles but still has the same problem of returning nil to my Objective-C class.</p>
  
  <p>The Objective-C protocol looks like this:</p>
  
  <pre><code>@protocol MySocialDelegate &lt;NSObject&gt;
  -(NSArray*)availableChannels;
  @end
  </code></pre>
  
  <p>The Swift delegate class looks like this:</p>
  
  <pre><code>class MySocialDelegateSwiftClass: NSObject, MySocialDelegate {
  
      private var socialChannels = NSMutableArray()
  
      func availableChannels() -&gt; [AnyObject]! {
  
          if ( self.socialChannels.count == 0 ) {
              let channel = ...getChannel()
              if ( channel != nil &amp;&amp; channel?.guid != nil ) {
                  self.socialChannels.addObject(channel)
              }
  
              if( someCondition ) {
                  let channel = ...getChannel()
                  if ( channel != nil &amp;&amp; channel?.guid != nil ) {
                      self.socialChannels.addObject(channel!)
                  }
              }
          }
  
          // self.socialChannels will contain 2 objects
  
          return self.socialChannels as [AnyObject]
      }
  }
  </code></pre>
  
  <p>And the Objective-C class that calls into that Swift delegate looks something like this:</p>
  
  <pre><code>ViewController *vc = [[UIStoryboard storyboardWithName... 
  vc.socialDelegate = instanceOfMySocialDelegateSwiftClass;
  if([vc.socialDelegate respondsToSelector:@selector(availableChannels)])
      vc.availableChannels = [vc.socialDelegate availableChannels];
  
  // vc.availableChannels will be nil
  </code></pre>