0

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 Answers 2

1

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.

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

Comments

0

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()

   }
}

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.