title: SwiftUI: How to make a CoreData entity conform to a protocol?
body: <p>I'm new to CoreData but managed to integrated it into my project. Now I need that one of my entities conform to a protocol I created. How can I achieve this? I tried but I can't get it right.</p>
  <p>My protocol:</p>
  <pre><code>protocol MyProtocol {
      init(text: String)
  }
  </code></pre>
  <p><code>CoreData</code> entity A:</p>
  <pre><code>@objc(A)
  public class A: NSManagedObject, MyProtocol {
      
      required init(text: String) {
          super.init()                 // Error!
          self.name = text
      }
      
  }
  
  extension A {
      @nonobjc public class func fetchRequest() -&gt; NSFetchRequest&lt;A&gt; {
          return NSFetchRequest&lt;A&gt;(entityName: &quot;A&quot;)
      }
  
      @NSManaged public var id: UUID
      @NSManaged public var name: String
  }
  
  extension A : Identifiable, CustomStringConvertible {
      var description: String { name }
  }
  </code></pre>
  <p>UPDATE:
  I need conformance to <code>MyProtocol</code> because I have a reusable view that takes an array of &quot;objects&quot; which may add/remove items to the array (this changes may not need to be persisted by CoreData, these may be just temporary objects). Therefore, I need to make sure that for any object I pass to this view there's a way to create the corresponding instance with this minimum requirement (a text property). See example below:</p>
  <pre><code>struct ReusableView&lt;Element: My Protocol&gt;: View {
      var data: [Element]
  
      var body: some View {
          //some code
  
          Button(action: {
              let newElement = Element(text: &quot;test&quot;)
              data.append(newElement)
          }, label: {
              Text(&quot;Add new Element&quot;)
          })
  
          //more code
  
          Text(&quot;some element name: \(data[0].description)&quot;)
      }
  }
  
  //... other file
  
  struct MainView: View {
      var entitiesA: [A] //CoreData entity A
      var entitiesB: [B] //CoreData entity B
  
      var body: some View {
          VStack {
              //some code
              ReusableView(entitiesA)
          
              //some code
              ReusableView(entitiesB)
          }
      }
  }
  </code></pre>
  <p>Also, I need to implement protocol <code>CustomStringConvertible</code> so that I'm able to access to a &quot;<code>description</code>&quot; property.</p>
  <p>All that for a CoreData object. Is this even possible? Am I doing it right?</p>
  <p>Thanks for your help!</p>