Reputation: 139
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..
Upvotes: 1
Views: 150
Reputation: 236528
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)
Upvotes: 2
Reputation: 299605
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).
Upvotes: 0