-1

Basically I am trying to implement a class for a Person and Person's pets. In it's very simple form Person class and Pet class would be like this:

class Person {
    var email  : String!
    var name   : String!
    var pets   : [Pet]!

    init(userName: String) {
        email = userName

       // load Person from CloudKit database
    }
}

class Pet {
    var name   : String!
    var breed  : String?
}

Now I want to be able to load all Pets related to the specific userName. If I have the above the class, that only holds one Pet. If I do an array like in the Person class, there is no Load method. The question is, should I create a new class Pets like below:

class Pets {
    var userName : String
    var pets     : [Pet]

    init(email: String) {
        // load all pets related to user here
    }
}

Does this make sense? Or is there a better way to structure the class? Is my question clear enough? Thanks for any help in advance.

oyalhi
  • 3,834
  • 4
  • 40
  • 45
  • I guess it does make sense yeah – martskins Feb 05 '15 at 11:46
  • `var init`, `String!` all over the place, `email = userName`, this isn't making much sense to me. I'd assume you want something like `func findPetsOf(userName: String, inContacts contacts: [Person]) -> [Pet]?` instead. No need for an extra class. At worst, make it return a tuple `(userName: String, pets: [Pet]?)`. – Jean-Philippe Pellet Feb 05 '15 at 11:58
  • `var init` was a typo, corrected. The real class is much longer than this. I tried to do a lean version here for the sake of discussion. You can consider it as a pseudo code. Where would findPetsOf function reside? Inside the Person class? If so, you are saying that all loading and saving logic of pets should be handled within the Person class. Am I correct? – oyalhi Feb 05 '15 at 12:26

1 Answers1

0

I'd be using structs not classes for my data model. Structs and Classes

I wouldn't use optionals unless I really had to, and there are a few use cases where you have to. I also wouldn't be using implicitly unwrapped optionals at all... i.e. ! It's an 'exclamation' for a reason. You should read up on when to use the different types of optionals.Why create implicitly unwrapped optionals

I wouldn't have a Pets class like you created. All this would be stored in your database to be queried ... possibly core data, or if you had some other class to hold the data it would be simply a dictionary/map of [String: [Pet]] and you could look up all the pets for a username from that dictionary/map

Community
  • 1
  • 1
bandejapaisa
  • 26,576
  • 13
  • 94
  • 112
  • I am using the CloudKit and actually your suggestion makes sense to me. I will simply create a new field of string array and save the pets there inside the Person table. As far as the optionals go, the code I supplied meant to be a pseudo code more or less. However, I will read up more about the optionals as well. Thank you. – oyalhi Feb 05 '15 at 12:47