title: CoreData - How to create duplicate object with existing object in swift
body: <p>This is the code for cloning the existing object but it crashed in line for (_,relatedObject) in <code>sourceSet.enumerated()</code></p>
  
  <pre><code>func clone(source:NSManagedObject,context:NSManagedObjectContext) -&gt; NSManagedObject{
          let entityName = source.entity.name
          let cloned = NSEntityDescription.insertNewObject(forEntityName: entityName!, into: context) as! IZExperiment
          //loop through all attributes and assign then to the clone
      let attributes = NSEntityDescription.entity(forEntityName: entityName!, in: context)?.attributesByName
      for (attrKey, _) in attributes! {
          cloned.setValue(source.value(forKey: attrKey), forKey: attrKey)
      }
  
  
      //Loop through all relationships, and clone them.
      let relationships = NSEntityDescription.entity(forEntityName: entityName!, in: context)?.relationshipsByName
      for (relKey, relValue) in relationships! {
          if relValue.isToMany {
              let sourceSet = mutableOrderedSetValue(forKey: relKey)
              let clonedSet = (copy() as AnyObject).mutableOrderedSetValue(forKey: relKey)
  //                let enumerator = sourceSet.enumerated()
  
  
              for (_,relatedObject) in sourceSet.enumerated()
              {
                  let clonedRelatedObject = (relatedObject as! NSManagedObject).shallowCopy()
                  clonedSet.add(clonedRelatedObject!)
  
              }
  
          } else {
              cloned.setValue(value(forKey: relKey), forKey: relKey)
          }
      }
      return cloned
  }
  
  
  
  extension NSManagedObject {
      func shallowCopy() -&gt; NSManagedObject? {
          guard let context = managedObjectContext, let entityName = entity.name else { return nil }
          let copy = NSEntityDescription.insertNewObject(forEntityName: entityName, into: context)
          let attributes = entity.attributesByName
          for (attrKey, _) in attributes {
              copy.setValue(value(forKey: attrKey), forKey: attrKey)
          }
          return copy
      }
  }
  </code></pre>