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

「真== 901」はあなたが意味するものではない可能性があります。多分 'productId == 901' ?? – danh

+0

@danh他に何かを入力するとエラーが発生します。 – Matt

+0

'ShoppingItem'はどのように定義されていますか? – vacawama

答えて

3

ループ項目のproductIdcontainsメソッドを使用して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({relevantProductIds.contains($ 0.productId)})。isEmpty' – vadian

+0

はい、@vadianはそれを行うべきです。しかし、 'forループ'とは異なり、最初のアイテムが見つかると停止するのではなく、すべてのアイテムをチェックします。 – vacawama

関連する問題