Error using of indexOf() from Checklists tutorial

Hi there,
Been trying to use the delegation pattern used in Checklists for my own app. I am managing a list of data file locations instead. I am pretty much using the code word for word. But I am getting this unusual error and I’m not exactly sure why.

My DataFile object is:

struct DataFile{ var name = "My Name" var description = "A new data file." var url = "http://www.google.com" var fileFormat: DataFileFormat = .JSON var authenticationRequired = false }

The error is below.

Can anyone explain why Matt’s “ChecklistItem” object has no problem with this but my DataFile object gives this error? I tried sending a closure to it like
if let index = myDataFiles.indexOf($0==item.name)
This made it compile but the condition won’t be met if the user changes the name property of the item object.

Really have no idea why this happens.

indexOf() needs compare “equality” of two objects. Checklist automatically gets this behavior because it extends NSObject.

If you don’t extend NSObject then you can make DataFile conform to the Equatable protocol, which involves defining an == operator for it.

That’s not something I wanted to touch on in this tutorial, and we needed NSObject anyway for the NSCoding stuff, so that’s why this isn’t a problem for Checklist.

Edit: I just noticed your DataFile is a struct. In that case you can’t use the NSObject trick. You’ll have to make the struct Equatable. But I’m not sure whether that makes sense in this case, because what does it mean for two DataFile objects to be equal? It might be easier to make it into a class that extends NSObject.

1 Like

Dear Matthias,

Thanks for taking the time to reply to this. Clear and concise answer.

One of the frustrating things about learning Swift is that the Struct vs Class arguments seem to extend way beyong just value type vs reference type. There are all these subtleties that are difficult for a newbie to grasp (along with code full of ? marks and ! marks :slight_smile:

Thanks for this. I’ll make it a class. And I’ve told you many times, but may as well take the opportunity again…I used iOS Apprenctice to learn Obj C and now re-using it for Swift…really extensive and nice piece of work. Something you can be immensely proud of.

Regards,
Jason

Thanks, Jason! :smiley: