Reputation: 61
So I have a class with the method isApplicableToList(list: [ShoppingItem]) -> Bool
. This should return true
if a discount can be applied based on the supplied list of product ids (i.e. a product must be matched to an offer) and the product IDs are 901 and 902.
I have attempted it but uncertain if done correctly or if there is a better way.
thanks in advance!
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
}
}
Upvotes: 0
Views: 282
Reputation: 154583
Loop through the items in your list and test if the item's productId
is in the list of applicableProductIds
using the contains
method. If none is found, return 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
}
Upvotes: 3