Search code examples
swiftclassrelationships

Swift: Define relationships between classes


I'm trying to figure out how to setup the relationship between two classes so that I'm able to determine the properties of one by knowing the other.

Let's say I have Owner and Pet, where the owner has a pet.

class Owner{
    let name: String
    var age: Int
    let petName: String

    init(name: String, age: Int, petName: String) {
        self.name = name
        self.age = age
        self.petName = petName
    }
}

class Pet{
    let petName: String
    var age: Int
    let petType: String

    init(petName: String, age: Int, petType: String) {
        self.petName = petName
        self.age = age
        self.petType = petType
        }    
    }

Assuming each petName is unique, I'd like to be able to do something like owner.petType where I can return the petType for the petName of the owner. Is this possible? Should I set the classes up differently?


Solution

  • You can set up your classes as such:

    class Owner {
        let name: String
        var age: Int
        var pet: Pet? //Owner might not have a pet - thus optional or can also have an array of pets
    
        init(name: String, age: Int, pet: Pet) {
            self.name = name
            self.age = age
            self.pet = pet
        }
    }
    
    class Pet {
        let name: String
        var age: Int
        let type: String
    
        init(name: String, age: Int, type: String) {
            self.name = name
            self.age = age
            self.type = type
        }    
    }