class someClass
{
// This is a list of restaurant names
var restaurantNames = ["Cafe Deadend", "Homei", "Teakha", "Cafe Loisl", "Petite Oyster", "For Kee Restaurant", "Po's Atelier", "Bourke Street Bakery", "Haigh's Chocolate", "Palomino Espresso", "Upstate", "Traif", "Graham Avenue Meats", "Waffle & Wolf", "Five Leaves", "Cafe Lore", "Confessional", "Barrafina", "Donostia", "Royal Oak", "Thai Cafe"]
// This is an array to record the restaurants I have visited
var restaurantIsVisited:[Bool] = [Bool](count: 21, repeatedValue: false)
// This is a function to set the restaurants I have visited
func setTheVisitedRestaurants(somenumber:Int)
{
self.restaurantIsVisited[somenumber] = true
}
}
let thisVisit = someClass()
thisVisit.setTheVisitedRestaurants(1)
let somearray = thisVisit.restaurantIsVisited
上面的代码在 playground 中没有错误。但是,如果我不知道餐厅总数是 21 家(可能有数百家,我不想数)怎么办?我尝试了以下代码来创建一个不可变的计算属性。但它不会工作,因为稍后该属性将被函数 setTheVisitedRestaurants
更改,并且它会返回一个错误。
// var restaurantIsVisited:[Bool]{
// return [Bool](count: restaurantNames.count, repeatedValue: false)
// }
简而言之,问题就像如何根据类中的其他属性创建一个可变属性。我是初学者,我真的尝试过。请帮忙!
最佳答案
使用 lazy
关键字声明 restaurantIsVisited
。这将确保它在第一次访问之前不会被创建,到那时您将能够向 restaurantNames
询问其 count
:
class someClass
{
// This is a list of restaurant names
var restaurantNames = ["Cafe Deadend", "Homei", "Teakha", "Cafe Loisl", "Petite Oyster", "For Kee Restaurant", "Po's Atelier", "Bourke Street Bakery", "Haigh's Chocolate", "Palomino Espresso", "Upstate", "Traif", "Graham Avenue Meats", "Waffle & Wolf", "Five Leaves", "Cafe Lore", "Confessional", "Barrafina", "Donostia", "Royal Oak", "Thai Cafe"]
// This is an array to record the restaurants I have visited
lazy var restaurantIsVisited:[Bool] = [Bool](count: self.restaurantNames.count, repeatedValue: false)
// This is a function to set the restaurants I have visited
func setTheVisitedRestaurants(somenumber:Int)
{
self.restaurantIsVisited[somenumber] = true
}
}
let thisVisit = someClass()
thisVisit.setTheVisitedRestaurants(1)
let somearray = thisVisit.restaurantIsVisited
println(somearray.count) // "21"
关于swift - 如何基于类中的其他属性创建变量属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30766409/