Search code examples
iosarraysswiftuiimageswift-array

Display UIImage within an array with custom class in Swift


I have a custom class Product defined as

class Product: NSObject {

var name: String
var priceLabel: String
var productImage: UIImage


init(name: String, priceLabel: String, productImage: UIImage) {
    self.name = name
    self.priceLabel = priceLabel
    self.productImage = productImage
    super.init()

   }
}

and I've created an array with that custom class

    let toy = [
    Product(name: "Car", priceLabel: "$5.00"),
    Product(name: "Train", priceLabel: "$2.50")
    ]

How would I insert the UIImage into that array? I would need to insert a different picture for each toy.

Thanks in advance


Solution

  • There are a few way to do it but with your code just example 1 will work:

    // Example 1:
    let toy = [
        Product(name: "Car", priceLabel: "$5.00", productImage:UIImage(named: "myImage.png")!),
        ...
        ]
    
    // Example 2:
    let product1 = Product(name: "Car", priceLabel: "$5.00")
    product1.productImage = UIImage(named: "myImage.png")!
    let toy = [
            product1,
            ...
            ]
    
    
    
    // Example 3:
    let toy = [
            Product(name: "Car", priceLabel: "$5.00"),
            ...
            ]
    if let prod = toy[0] {
        prod.productImage = UIImage(named: "myImage.png")!
    }
    

    You have just one init which takes 3 parameters so if you create object like that:

    Product(name: "Car", priceLabel: "$5.00")
    

    it won't compile because you have not initialiser which accept just two parameters.