如何返回布尔值?
问题描述:
所以我有一个类的方法isApplicableToList(list: [ShoppingItem]) -> Bool
。如果可以根据提供的产品ID列表应用折扣(即,产品必须与报价匹配)并且产品ID是901和902,则应该返回true
。如何返回布尔值?
我已经尝试过但不确定是否完成正确或者如果有更好的方法。
在此先感谢!
class HalfPriceOffer :Offer {
init(){
super.init(name: "Half Price on Wine")
applicableProductIds = [901,902];
}
override func isApplicableToList(list: [ShoppingItem]) -> Bool {
//should return true if a dicount can be applied based on the supplied list of product ids (i.e. a product must be matched to an offer)
if true == 901 {
return true
}
if true == 902 {
return true
}
else {
return false
}
}
}
ShoppingItem
class ShoppingItem {
var name :String
var priceInPence :Int
var productId :Int
init(name:String, price:Int, productId:Int){
self.name = name
self.priceInPence = price
self.productId = productId
}
}
答
遍历列表和测试的项目,如果该项目的productId
是使用contains
方法的applicableProductIds
名单。如果没有找到,请返回false
。
override func isApplicableToList(list: [ShoppingItem]) -> Bool {
//should return true if a dicount can be applied based on the supplied list of product ids (i.e. a product must be matched to an offer)
for item in list {
if applicableProductIds.contains(item.productId) {
return true
}
}
// didn't find one
return false
}
'true == 901'很可能不是你的意思。也许'productId == 901'? – danh
@danh我输入其他内容时出现错误。 – Matt
如何定义ShoppingItem? – vacawama