0

我有一个自定义类Product定义为

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

   }
}

我用那个自定义类创建了一个数组

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

我将如何将 UIImage 插入该数组?我需要为每个玩具插入不同的图片。

提前致谢

4

2 回答 2

1

有几种方法可以做到这一点,但使用您的代码,只需示例 1 即可:

// 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")!
}

您只有一个带有 3 个参数的 init,因此如果您创建这样的对象:

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

它不会编译,因为您没有只接受两个参数的初始化程序。

于 2015-07-22T13:47:56.350 回答
0

试试这个:

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

旁注:如果你想让你的初始化程序更加动态,请使用默认参数。

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

   }
}
于 2015-07-22T13:57:09.290 回答