How to insert new data to entity in Swift?
<p>In Swift previously, I was able to use a code like this to add new data to my &quot;TestEntity&quot; in my data model.</p>
<p><code>NSManagedObject</code> was created for my &quot;TestEntity&quot; and I was able to set its attributes with the &quot;dot&quot; syntax</p>
<p>At the end, I would save the context</p>
<pre><code>let entity=NSEntityDescription.insertNewObject(forEntityName: &quot;TestEntity&quot;, into: context) as! TestEntity
entity.testAttribute=&quot;test value&quot;
context.save()
</code></pre>
<p>This code does not work in Swift 3. When I run it, i get the following runtime error:</p>
<blockquote>
<p>Could not cast value of type 'NSManagedObject_TestEntity_'
(0x175306b0) to 'testCoreData.TestEntity' (0xd6bb8). 2016-06-19
11:07:52.305195 testCoreData[689:264453] Could not cast value of type
'NSManagedObject_TestEntity_' (0x175306b0) to
'testCoreData.TestEntity' (0xd6bb8)</p>
</blockquote>
<p>Can anyone shed some light on how this should be done in Swift 3?</p>
<p>The second part of the question is how to access the data again. the following code ends with an error:</p>
<blockquote>
<p>fatal error: <code>NSArray</code> element failed to match the Swift Array Element type</p>
</blockquote>
<pre><code>let fr:NSFetchRequest&lt;TestEntity&gt;=TestEntity.fetchRequest()
        
do {
   let searchResults=try context.fetch(fr)
   if let results=searchResults {
      for result in results {
         print(&quot;testAtt = \(result.testAtt)&quot;)
      }
   }
} catch {
            
}
</code></pre>