Display UIImage within an array with custom class in Swift

716 views Asked by At

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

2

There are 2 answers

0
Greg On BEST ANSWER

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.

0
villy393 On

Try this:

let newArray = toy.map{Product(name: $0.name, priceLabel: $0.priceLabel, productImage:UIImage(named: "myImage.png")!)}

side note: If you want to make your initialiser more dynamic use default parameters.

init(name: String = "DefaultName", priceLabel: String = "DefaultName", productImage: UIImage = UIImage(named: "DefaultImage")) {
    self.name = name
    self.priceLabel = priceLabel
    self.productImage = productImage
    super.init()

   }
}