嵌套字典奇怪的行为

时间:2014-10-28 11:07:12

标签: swift

我想制作数字地图

代码:

class figures {
    var maps : [NSDictionary]
    init() {
        self.maps = [
            [
                "map" : [
                    [ "x" : -0.5, "y" : -0.5]
                ],
                "color" : UIColor.redColor()
            ],
            [
                "map" : [
                    [ "x" : 0, "y" : 0],  [ "x" : 0, "y" : -1],  [ "x" : -1, "y" : 0],  [ "x" : -1, "y" : -1]
                ],
                "color" : UIColor.blueColor()
            ],
            [
                "map" : [
                    [ "x" : 0, "y" : -0.5], [ "x" : -1, "y" : -0.5]
                ],
                "color" : UIColor.yellowColor()
            ]
        ]
    }
}

此代码有效,但我想在此字典中添加1个数字,例如:

        [
            "map" : [
                [ "x" : -1, "y" : -0.5], [ "x" : 0.5, "y" : -0.5], [ "x" : -0.5, "y" : -0.5]
            ],
            "color" : UIColor.cyanColor()
        ]

现在我收到以下错误:

Could not find an overload for '-' that accepts the supplied arguments

但是如果在最后一个dict中将x替换为-0.5,那么它再次有效

 [
            "map" : [
                [ "x" : -1, "y" : -0.5], [ "x" : 0.5, "y" : -0.5], [ "x" : 0.5, "y" : -0.5]
            ],
            "color" : UIColor.cyanColor()
        ]

发生了什么事?有人帮忙

1 个答案:

答案 0 :(得分:0)

swift编译器已经知道像这样的大型语句的问题。更好地逐步构建阵列:

self.maps.append([
    "map" : [
                [ "x" : -0.5, "y" : -0.5]
            ],
            "color" : UIColor.redColor()
])

self.maps.append([
    "map" : [
                [ "x" : 0, "y" : 0],  [ "x" : 0, "y" : -1],  [ "x" : -1, "y" : 0],  [ "x" : -1, "y" : -1]
            ],
            "color" : UIColor.blueColor()
])

...