title: Swift and NSCoding: Encoding an array of objects conforming to a class-only protocol
body: <p>I have a class, <code>StandardObject</code>, that conforms to the protocol <code>Object</code>. Another class, <code>ObjectManager</code>, has a property called <code>objects</code> which is an array containing instances of <code>Object</code>. Both <code>StandardObject</code> and <code>ObjectManager</code> are subclasses of <code>NSObject</code> and conform to <code>NSCoding</code>.</p>
  
  <p>When I try to encode the <code>objects</code> property of <code>ObjectManager</code> in <code>encodeWithCoder:</code>, I receive an error:</p>
  
  <pre><code>cannot convert value of type '[Object]' to expected argument type 'AnyObject?'
  </code></pre>
  
  <p>Here is my code:</p>
  
  <p><code>ObjectManager</code>:</p>
  
  <pre><code>class ObjectManager: NSObject, NSCoding {
  
      var objects = [Object]()
  
      required init?(coder aDecoder: NSCoder) {
  
      }
  
      func encodeWithCoder(aCoder: NSCoder) {
          aCoder.encodeObject(objects, forKey: "Objects") //// ERROR HERE
      }
  
  }
  </code></pre>
  
  <p><code>Object</code> protocol:</p>
  
  <pre><code>protocol Object: class, NSCoding {
      // Currently completely empty
  }
  </code></pre>
  
  <p><code>StandardObject</code>:</p>
  
  <pre><code>class StandardObject: NSObject, Object {
  
      required init?(coder aDecoder: NSCoder) {
  
      }
  
      func encodeWithCoder(aCoder: NSCoder) {
  
      }
  
  }
  </code></pre>
  
  <p>I know it has to do with the fact that you can only encode objects (or arrays of them), not structs, enums, or in this case, protocols. However, the <code>Object</code> protocol's declaration is:</p>
  
  <pre><code>protocol Object: class, NSCoding
  </code></pre>
  
  <p>which means that only classes can conform to this protocol.</p>
  
  <p>Shouldn't that mean that there are only instances of classes in the <code>objects</code> array? Why can't it be encoded?</p>
  
  <p>I have also tried casting the array to an NSArray before encoding, but I get this error:</p>
  
  <pre><code>cannot convert value of type '[Object]' to type 'NSArray' in coercion
  </code></pre>
  
  <p>So here are my two questions:</p>
  
  <ol>
  <li>If I made the <code>Object</code> protocol only have objects conform to it, shouldn't an array of <code>Object</code> be an array of objects?</li>
  <li>If question 1 isn't possible for some reason, how do you convert the array of <code>Object</code> to be able to be encoded with <code>NSCoding</code>?</li>
  </ol>