对象数组 - Swift

时间:2017-03-08 23:07:41

标签: swift class object dictionary

我想创建一个我创建的对象的arrray。我将包括对象的示例。但是,每次我尝试,我都会收到错误:“预期声明”。我也得到一个错误,该阵列未被识别。这是因为我必须在数组中的某处提到类吗?

class ShapeColour : NSObject {
    var colour:String
    var shape:String
    var image:UIImage

    init(color: String, shape: String, image: UIImage) {
        self.colour = color
        self.shape = shape
        self.image = image
    }

}
上面是

类,下面是一个例子

 let redTriangleObject = ShapeColour(color: "red", shape: "triangle", image: UIImage(named: "redTriangle.png")!)

Bellow是数组

mainShapeDict = [blueSquareObject,blueCircleObject,blueTriangleObject,redSquareObject,redCircleObject,redTriangleObject,yellowSquareObject,yellowCircleObject,yellowTriangleObject]

谢谢!

2 个答案:

答案 0 :(得分:2)

您只需在let之前说出mainShapeDict

let mainShapeDict = [blueSquareObject, blueCircleObject, blueTriangleObject, redSquareObject, redCircleObject, redTriangleObject, yellowSquareObject, yellowCircleObject, yellowTriangleObject]

这就是为什么它说"预期宣言",因为你还没有在我猜测的任何其他代码中声明mainShapeDict。

答案 1 :(得分:1)

你应该先声明数组 像这样

apage.organization.domain

然后你可以添加" ShapeColour"使用.append方法的对象

var mainShapeDict : [ShapeColour] = [ShapeColour]()

注意:mainShapeDict是一个数组而不是字典