0

unable to get Array of dictionary value

this is my model

public var featured_product : Array<Featured_product>?

    public class Featured_product {
    public var wishlist : wishlist?
    }

     required public init?(dictionary: NSDictionary) {
       if (dictionary["wishlist"] != nil) { wishlist = Aswagna.wishlist(dictionary: dictionary["wishlist"] as? NSDictionary ?? NSDictionary())}
   }

public class wishlist {
public var id : Int?
}

here i want wishlist-> id.. for that i have tried like below

@IBAction func addToWishList(_ sender: UIButton){
 
    if let data = self.homDB?.result?.product?.featured_product{

        for wishlistData in data.wishlist ?? []{

            idFav = wishlistData["id"]
        }
    }
    
}

error in for loop data.wishlist

Value of type '[Featured_product]' has no member 'wishlist'

how do i get wishlist id.. please do help

Edit: addToWishList is the collectionview cell button action.. i have given its action to HomeVC from storyboard cell

class HomeVC: UIViewController{
var homDB = HomeDataModel(dictionary: NSDictionary())
@IBAction func addToWishList(_ sender: UIButton){
 //here i need selected button's wishlist id
  
  idFav = self.homDB?.result?.product?.featured_product?[sender.tag].wishlist?.id
  print("wishlist id \(idFav)")
 }

}

if i do like above then print("wishlist id \(idFav)") getting nil.. where am i wrong.. pls do help.

1 Answer 1

1

The first error is straightforward. The error message states thatdata is an array of Featured_product and that the array has no member wishlist. You need to access the individual array element before accessing wishlist:

    for wishlistData in data ?? []{

        idFav = wishlistData["wishlist"].id
    }

Regarding the second one, I would suggest to unwrap each element of your chain one at time to get a better understanding of which one is nil.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.