2016-12-04 278 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