gpt4 book ai didi

arrays - 如何使用实例变量访问另一个变量中的对象并返回

转载 作者:行者123 更新时间:2023-11-30 11:32:12 27 4
gpt4 key购买 nike

如何使用实例变量访问另一个变量中的对象并返回

class Tyre {
let name: String
var owner: Vehicle?
init(name: String){
self.name = name
}
}

class Vehicle {
var name: String
var tyres: [Tyre] = []

var stringIds = "";
var tyreNames : () -> String = {
// let allTyres = (tyres.map{String($0)}).joined(separator: ",")
print(tyres) // unable to acess tyres here
return ""
}

init(name: String){
self.name = name
}

func adopt(tyre: Tyre){
tyres.append(tyre)
tyre.owner = self
}
}

var myCar = Vehicle(name: "Honda")
var tyre = Tyre(name: "MRF")
myCar.adopt(tyre: tyre)
tyre = Tyre(name: "CFP")
myCar.adopt(tyre: tyre)
print(myCar.tyreNames())

无法访问车辆类别中的轮胎以打印该车辆类别的所有轮胎:

error : Instance member 'tyres' cannot be used on type 'Vehicle'

最佳答案

而不是像闭包那样将 tyreNames 声明为计算变量

var tyreNames : String {
return tyres.map{ $0.name }.joined(separator: ", ")
}

并调用它

print(myCar.tyreNames)

关于arrays - 如何使用实例变量访问另一个变量中的对象并返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50148964/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com