Arrays 复制Swift 4中NSManagedObject对象的数组

Arrays 复制Swift 4中NSManagedObject对象的数组,arrays,swift,core-data,copy,swift4,Arrays,Swift,Core Data,Copy,Swift4,我有一个NSManagedObject的数组,我想将它们复制到一个新数组中,以便对它们进行操作,而不是在用户完成操作后保存更改 数组: var origQuestions: [Questions]? self.origQuestions = MainDb.sharedInstance.randomQuestions(entity: "Questions", count: self.questionToShow) NSMutableArray *questionsCopy = [[NSMuta

我有一个
NSManagedObject的
数组,我想将它们复制到一个新数组中,以便对它们进行操作,而不是在用户完成操作后保存更改

数组:

var origQuestions: [Questions]?
self.origQuestions = MainDb.sharedInstance.randomQuestions(entity: "Questions", count: self.questionToShow)
NSMutableArray *questionsCopy = [[NSMutableArray alloc] initWithArray:self.origQuestions copyItems:YES];
这是我从CoreData检索数据的方式:

var origQuestions: [Questions]?
self.origQuestions = MainDb.sharedInstance.randomQuestions(entity: "Questions", count: self.questionToShow)
NSMutableArray *questionsCopy = [[NSMutableArray alloc] initWithArray:self.origQuestions copyItems:YES];
这是我在Objective-C中需要的,但我想知道如何在Swift 4中做到这一点:

var origQuestions: [Questions]?
self.origQuestions = MainDb.sharedInstance.randomQuestions(entity: "Questions", count: self.questionToShow)
NSMutableArray *questionsCopy = [[NSMutableArray alloc] initWithArray:self.origQuestions copyItems:YES];

要将Objective-C代码转换为Swift,您需要:

var questionsCopy = NSArray(array: origQuestions, copyItems:true) as! [Questions]
但是,由于您将
origQuestions
声明为可选,因此需要:

var questionsCopy = origQuestions != nil ? NSArray(array: origQuestions!, copyItems:true) as? [Questions] : nil

对于
NSManagedObject
而言,这是否完全有效(Objective-C或Swift)是另一个问题。请参阅及其快速答案,以获取专门涉及深度复制
NSManagedObject
实例的代码。

您能否通过展示一些您迄今为止尝试过的代码来缩小您的问题范围?@Christophe我编辑了我的问题。请查收。谢谢好啊swift答案有帮助吗?我实际上使用了你在答案中给出的问题的链接,找到了swift 4的方法。回答得好!谢谢出于好奇,你最初为什么想要Objective-C系列?在我的答案中翻译后,你有没有在Swift中尝试过,结果是什么?我不想要Obj-C这一行。我只是想展示一下我过去是如何在Obj-C中使用它的,但不知道如何在Swift中使用它。因为在Swift中,我想您需要以不同的方式克隆阵列。