Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays Swift:无法从另一个对象在数组中添加元素_Arrays_Swift_Macos Catalina - Fatal编程技术网

Arrays Swift:无法从另一个对象在数组中添加元素

Arrays Swift:无法从另一个对象在数组中添加元素,arrays,swift,macos-catalina,Arrays,Swift,Macos Catalina,我正在努力学习快速的语法。我想向数组中添加对象,但有语法错误。 数组位于类文档中,应该添加对象的类位于类Viewcontroller中 数组的类型为内容: public class Content: NSObject { @objc var bankAccSender: String? @objc var bankAccReceiver: String? 文件中的声明: class Document: NSDocument { var content=[C

我正在努力学习快速的语法。我想向数组中添加对象,但有语法错误。 数组位于类文档中,应该添加对象的类位于类Viewcontroller中

数组的类型为内容:

public class Content: NSObject  {
    @objc var bankAccSender: String?
    @objc var bankAccReceiver: String?
文件中的声明:

class Document: NSDocument  {
    
    var content=[Content]()

    override init() {
        super.init()
        self.content = [Content]()
        
        // force one data record to insert into  content 
        content += [Content (… )]      // checked with debugger
ViewController已指定所表示的对象

contentVC.representedObject = content
但在ViewController中添加数据会导致编译器错误“表达式类型不明确,没有更多上下文”:

var posting = Content(…)
self.representedObject.append(posting)

希望您能提供帮助。

representedObject
的类型为
Any?
,在Swift中很难使用该类型。因为您已经有了
content
属性,我可能会调整该属性,然后将其重新分配给
representedObject

您也可以尝试此操作(未测试),只要您确定类型始终为
[Content]

(self.representedObject as! [Content]).append(posting)
您可能需要更复杂的解决方案,如:

(self.representedObject as! [Content]?)!.append(posting)

正如我所说,
Any?
是一种令人难以置信的讨厌类型。你可能想把它包装成一个函数。或者我建议你可以避免使用
representedObject
。在很多情况下,你不需要它。它通常只是一种方便(在ObjC中;在Swift中,很难使用).

您不能将元素附加到类型为
Any
的对象。您需要的是用新集合替换现有值:

representedObject = (representedObject as? [Content] ?? []) + CollectionOfOne(posting)

谢谢Rob,这真的很棘手。不幸的是,你们两个语句都会引发错误。谢谢Rob,这真的很棘手。不幸的是,你们两个语句都会引发错误。语句是:“不能对[content]类型的不可变值使用mutating member”。我将看看Leo的回答是否有帮助。