elswat elswat - 7 months ago 14
Swift Question

Property 'title' not found on object of type 'id'

The following line is what causes the error:

NSLog(@"Title: %@", self.events[0].title);


I declared the array events earlier in the file, and I wanted to print out the event title in order to do some debugging. However, I get an error. I do not understand why I am getting this error because each event has a title property as shown in the following function.

@IBAction func addMedicine(sender: AnyObject) {
objectC!.events = NSMutableArray()
let event: DPCalendarEvent = DPCalendarEvent(title: nameText.text, startTime: startDatePicker.date, endTime: startDatePicker.date, colorIndex: 1)
objectC!.events.addObject(event)
}


I was able to use events[0].title in the above function earlier when I included a NSLog statement in the function. Any idea what is causing the error? I was thinking that the error is that the two arrays aren't the same array, but I am not sure how to make the array accessible from both files.
Note: The first line of code is in an Objective-C file and the second block of code is in a Swift file.

Answer

I do not understand why I am getting this error because each event has a title property

Yes, but self.events[0] is not an event — at least, not as far as the compiler knows. Subscripting an array gives an id, and an id has no properties. And you have given the poor old compiler nothing further to go on. If this thing is a DPCalendarEvent, cast it to a DPCalendarEvent:

NSLog(@"Title: %@", ((DPCalendarEvent*)self.events[0]).title);

Alternatively, use Objective-C's new lightweight generics notation to say what events is an array of.