简体   繁体   English

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

[英]How to Properly Declare Array of Custom Objects in Swift?

Here is my custom class...not sure if I'm missing anything in it... 这是我的自定义类...不确定我是否缺少任何内容...

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
    }
}

I'm trying to instantiate here... 我正在尝试在此处实例化...

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

I didn't include the rest of the ViewController class, because I didn't think it was necessary. 我没有包括ViewController类的其余部分,因为我认为没有必要。

The error occurs when I attempt to assign a value to foundation[0].Brand 当我尝试为Foundation [0]分配值时发生错误。

Appreciate your help in advance! 提前感谢您的帮助!

First, I'm going to assume you didn't want 2d arrays. 首先,我假设您不想要2D数组。 If you did, I'll answer your question from that perspective below. 如果您这样做了,我将从下面的角度回答您的问题。

    var foundation = [baseMakeUp]()

Creates an empty array of baseMakeUp called foundation. 创建一个空的baseMakeUp数组,称为Foundation。 You can't use subscripting to add elements to an array, you can only use it to change existing elements. 您不能使用下标将元素添加到数组,只能使用它来更改现有元素。 Since your array is empty you add elements with append. 由于数组为空,因此需要添加带有append的元素。

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

Since you don't have a baseMakeUp initializer that allows you to pass a rating that element's rating is 0. However since you appended it to your array you can now use subscripting to change it's Rating variable like this: 由于您没有baseMakeUp初始化程序,该初始化程序可让您传递该元素的等级为0的等级。但是,由于将其附加到数组后,现在可以使用下标来更改它的Rating变量,如下所示:

foundation[0].Rating = 3

If you did intend for 2d arrays. 如果您确实打算使用2D阵列。

    var foundation = [[baseMakeUp]]()

To create the array 创建数组

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

The first line appends an empty array to your top level array. 第一行将一个空数组追加到顶级数组。 The second line appends a baseMakeUp to the array added in the first line. 第二行将baseMakeUp追加到第一行中添加的数组。 The third line uses subscripting to change the Rating of the first element in the first array of your 2d array. 第三行使用下标更改2d数组的第一个数组中第一个元素的评级。

Hopefully that helps with your problem. 希望这可以帮助您解决问题。

Additionally 另外

I was going to add points 1 and 2 from jday001s answer here, but you should check out their answer as well. 我打算在这里从jday001s答案中添加点1和2,但是您也应该查看它们的答案。

Edit 编辑

I just realized that you're trying to add elements to your arrays in the wrong scope. 我只是意识到您正在尝试在错误的范围内将元素添加到数组中。

You'll have to move your 您必须移动您的

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

inside a function and call it yourself or place them inside something like viewDidLoad 在函数内部并自己调用,或将其放在诸如viewDidLoad之类的内部

eg: 例如:

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    var foundation = [baseMakeUp]()

    override func viewDidLoad() {
        super.viewDidLoad()

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

Hopefully that's helpful. 希望这会有所帮助。

You have a few things going on here: 您在这里发生了一些事情:

  1. You are missing some naming conventions. 您缺少一些命名约定。 Class names should be capitalized ( baseMakeUp should be BaseMakeUp ). 类名应大写( baseMakeUp应为BaseMakeUp )。
  2. Class vars should be lower case ( image , brand , color , rating ). 类别var必须使用小写字母( imagebrandcolorrating )。 Also brand & color in the init method. 以及init方法中的brandcolor
  3. Do you intend for your foundation array to be multidimensional? 您打算使foundation阵列具有多维性吗? If you just want a regular array, I'd go with something like: 如果您只想使用常规数组,则可以使用以下方法:

     var foundation = [BaseMakeup]? 
  4. As the other answer says, you also need to instantiate BaseMakeup objects using your init method: 正如另一个答案所说,您还需要使用init方法实例化BaseMakeup对象:

     let aBaseMakeup = BaseMakeup(brand: "Revlon", color: "Red") 
  5. After that, you can add BaseMakeup objects to your array like this: 之后,您可以像下面这样将BaseMakeup对象添加到您的数组中:

     foundation?.append(aBaseMakeup) 

Hopefully I'm understanding what you are trying to accomplish. 希望我了解您正在努力实现的目标。

First Create a custom class... 首先创建一个自定义类...

import Foundation

class ClassName{

  var id: Int?
  var name: String?
  var category_name: String?
  var price: Double?

   init(json: JSON) {
        self.id = json["id"].int
        self.name = json["name"].string
        self.category_name = json["category_name"].string
        self.price = json["price"].double
}

}

Use can use this Class in viewcontroller by following lines 使用可以通过以下几行在viewcontroller中使用该类

var arrayName:Array<yourclassname> = Array()
print("/(yourclaseename[0].name)")

You need to instantiate your class object 您需要实例化您的类对象

example: 例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM