[英]How to initialise a variable in Struct just once in Swift
This is my struct: 这是我的结构:
struct BookingDetailViewModel {
private let bookingDetail:BookingDetail
init(bookingDetail:BookingDetail) {
self.bookingDetail = bookingDetail
}
var pricingCharts:[PricingChartViewModel] {
let chartArray = bookingDetail.priceCharts
var pricingChartArray:[PricingChartViewModel] = Array()
for chart in chartArray {
let pricingChartViewModel = PricingChartViewModel(pricingChart: chart)
pricingChartArray.append(pricingChartViewModel)
}
return pricingChartArray
}
}
This is my viewModel and when I try to access the value of bookingDetailViewModel.pricingCharts , the array inside is computed again and again when accessed from tableView datasource which doesn't make any sense to me because the pricingCharts will always remain the same. 这是我的viewModel,当我尝试访问bookingDetailViewModel.pricingCharts的值时,从tableView数据源访问时,一次又一次地计算内部数组,这对我来说没有任何意义,因为priceingCharts将始终保持不变。
Is there any possible way of computing this pricingCharts just once, so I can get a better performance? 有没有可能只计算一次此定价图表的方法,这样我可以获得更好的性能?
Am I doing it correctly or should I follow some other pattern while setting the pricingCharts. 我是在正确执行设置定价图表时还是遵循其他模式?
What you have is a custom getter for your pricingCharts
, and it behaves as it should - it recalculates (ie gets ) its value every time it is needed. 您拥有的是为pricingCharts
定制的getter,并且它的行为符合pricingCharts
-每次需要时都会重新计算(即获取 )其值。
What you need/want is a lazy var
. 您需要/想要的是一个lazy var
。 Simply change your pricingCharts
to : 只需将您的pricingCharts
更改为:
lazy var pricingCharts:[PricingChartViewModel] = {
let chartArray = self.bookingDetail.priceCharts
var pricingChartArray:[PricingChartViewModel] = Array()
for chart in chartArray {
let pricingChartViewModel = PricingChartViewModel(pricingChart: chart)
pricingChartArray.append(pricingChartViewModel)
}
return pricingChartArray
}()
There were three changes made : 进行了三处更改:
lazy
keyword before var
var
之前的lazy
关键字 =
sign between type and block =
类型和块之间的符号 ()
braces at the end of the block ()
括号的结尾 As usually you can red more in the docs. 通常,您可以在文档中添加更多内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.