Swift:定义类之间的关系

Swift: Define relationships between classes

我正在尝试弄清楚如何设置两个 类 之间的关系,以便我能够通过了解另一个来确定一个的属性。

假设我有主人和宠物,主人有一只宠物。

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
        }    
    }

假设每个 petName 都是唯一的,我希望能够做类似 owner.petType 的事情,我可以 return 主人的 petName 的 petType。这可能吗?我应该以不同的方式设置 类 吗?

您可以这样设置 类:

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
    }    
}