2016-12-04 220 views
0

所以我有一个类的方法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 
    } 
} 
+1

'true == 901'很可能不是你的意思。也许'productId == 901'? – danh

+0

@danh我输入其他内容时出现错误。 – Matt

+0

如何定义ShoppingItem? – vacawama

回答

3

遍历列表和测试的项目,如果该项目的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 
} 
+0

非常感谢!现在一切都说得通了! – Matt

+1

或在一行中:'return!list.filter({applicableProductIds.contains($ productproduct)})。isEmpty' – vadian

+0

是的,@vadian应该这样做。与'for循环'不同,它会检查每个项目,而不是在找到第一个项目时停止。 – vacawama