如何在Swift中正确声明自定义对象数组?

这是我的自定义类…不知道如果我错过了任何东西…

import UIKit class baseMakeUp { var Image = UIImage() var Brand: String var Color: String var Rating: Int = 0 init (Brand: String, Color: String) { self.Brand = Brand self.Color = Color } } 

我想在这里实例化…

 import UIKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } let cellIdentifier = "cellIdentifier" var foundation: [[baseMakeUp]] var blush: [[baseMakeUp]] var eyes: [[baseMakeUp]] var lips: [[baseMakeUp]] var nails: [[baseMakeUp]] // put some test data in makeup arrays here... foundation[0].Brand = "Revlon" -------------> "Expected declaration" error. foundation[0].Color = "Red" foundation[0].Rating = 3 foundation[1].Brand = "MAC" foundation[1].Color = "Blue" foundation[1].Rating = 4 

我没有包含ViewController类的其余部分,因为我不认为这是必要的。

当我尝试为基础[0]。品牌分配一个值时,会发生错误

提前感谢您的帮助!

首先,我假设你不想要二维数组。 如果是的话,我会从下面的这个angular度回答你的问题。

  var foundation = [baseMakeUp]() 

创build一个名为foundation的空数组。 您不能使用下标将元素添加到数组,只能使用它来更改现有的元素。 由于你的数组是空的,你可以使用append添加元素。

  foundation.append(baseMakeUp(Brand: "Brand", Color: "Color")) 

因为你没有一个baseMakeUp初始值设定项,允许你传递该元素的评级为0的评级。然而,由于你将它附加到你的数组,你现在可以使用下标来改变它的Ratingvariables,如下所示:

 foundation[0].Rating = 3 

如果你打算二维数组。

  var foundation = [[baseMakeUp]]() 

创build数组

  foundation.append([]) foundation[0].append(baseMakeUp(Brand: "Brand", Color: "Color")) foundation[0][0].Rating = 3 

第一行将一个空数组添加到顶层数组中。 第二行将baseMakeUp追加到第一行添加的数组中。 第三行使用下标来更改第二个数组第一个数组中第一个元素的等级。

希望能帮助你解决问题。

另外

我打算从jday001s的答案中join第1点和第2点的答案,但你也应该查看他们的答案。

编辑

我只是意识到你正试图添加元素到你的数组在错误的范围内。

你必须移动你的

 foundation.append(baseMakeUp(Brand: "Brand", Color: "Color") 

在函数内部调用它,或者把它们放在类似viewDidLoad的东西里面

例如:

 class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { var foundation = [baseMakeUp]() override func viewDidLoad() { super.viewDidLoad() foundation.append(baseMakeUp(Brand: "Brand", Color: "Color") foundation[0].Rating = 3 } } 

希望这是有帮助的。

你在这里有几件事情:

  1. 您错过了一些命名约定。 类名称应该大写( baseMakeUp应该是BaseMakeUp )。
  2. class级variables应该是小写( imagebrandcolorrating )。 在init方法中也是brandcolor
  3. 你打算让你的foundationarrays是多维的? 如果你只是想要一个普通的数组,我会用类似的东西:

     var foundation = [BaseMakeup]? 
  4. 正如另一个答案所说,你还需要使用init方法实例化BaseMakeup对象:

     let aBaseMakeup = BaseMakeup(brand: "Revlon", color: "Red") 
  5. 之后,您可以像这样将BaseMakeup对象添加到您的数组中:

     foundation?.append(aBaseMakeup) 

希望我能理解你正在努力完成的事情。

你需要实例化你的类对象

例:

 var foundation = baseMakeUp(Brand: "Some Brand", Color: "Red")