1

I am struggeling with swift syntax . I want to add objects to an array but I have syntax errors. The array is located in class Document, and the class that should add objects is in class Viewcontroller.

The array is of type Content:

public class Content: NSObject  {
    @objc var bankAccSender: String?
    @objc var bankAccReceiver: String?

Declaration snippest in Document:

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

The ViewController has assigned the represented Object

contentVC.representedObject = content

But adding data in ViewController gives a compiler error „Type of expression is ambiguous without more context“:

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

Hope you can help..

0

2 Answers 2

2

You can't append an element to an object of type Any. What you need is to replace the existing value with a new collection:

representedObject = (representedObject as? [Content] ?? []) + CollectionOfOne(posting)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Rob, it is really tricky. Unfortunately, both of your statements raises errors. Statement is : "Cannot use mutating member on immutable value of type [content]". I will see if Leo's answer helps.
0

representedObject is of type Any?, which is a very difficult type to work with in Swift. Since you already have a content property, I would probably adjust that, and then re-assign it to representedObject.

You can also try this (untested), as long as you are certain that the type is always [Content]:

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

It's possible you'll need some more complex like this:

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

As I said, Any? is an incredibly obnoxious type. You probably want to wrap this up into a function. Or I you can avoid using representedObject, then I would recommend that. In many cases you don't need it. It's often just a convenience (in ObjC; in Swift, it's very hard to use).

1 Comment

Thanks Rob, it is really tricky. Unfortunately, both of you statements raises errors.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.