我试图弄清楚如何设置两个类之间的关系,以便我能够通过了解另一个来确定一个属性。
让我们说我有主人和宠物,主人有宠物。
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这样做,我可以返回所有者petName的petType。这可能吗?我应该以不同的方式设置课程吗?
答案 0 :(得分:0)
您可以这样设置课程:
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
}
}