没有名为' subscript'的成员

时间:2015-04-11 17:49:01

标签: swift

我正在构建一些东西,一切正常,直到Swift 1.2问世。我做了一些更改,但仍然有一行代码很好。我不明白为什么会这样:

let swiftArray = positionDictionary.objectForKey["positions"] as? [AnyObject]

它给了我一个错误:

  

'(AnyObject) - > AnyObject&#39?;没有名为'下标'

的成员

我也试过用这个:

let swiftArray = positionDictionary.objectForKey?["positions"] as? [AnyObject]

然后我收到一个错误说:

  

后缀的操作数'?'应该有一个可选的类型; type是'(AnyObject) - > AnyObject'?

我真的很困惑......任何人都可以帮忙吗?

func addOrbsToForeground() {


        let orbPlistPath = NSBundle.mainBundle().pathForResource("orbs", ofType: "plist")
        let orbDataDictionary : NSDictionary? = NSDictionary(contentsOfFile: orbPlistPath!)

        if let positionDictionary = orbDataDictionary {

            let swiftArray = positionDictionary.objectForKey["positions"] as? [AnyObject]

            let downcastedArray = swiftArray as? [NSArray]

            for position in downcastedArray {

                let orbNode = Orb(textureAtlas: textureAtlas)
                let x = position.objectForKey("x") as CGFloat
                let y = position.objectForKey("y") as CGFloat
                orbNode.position = CGPointMake(x,y)
                foregroundNode!.addChild(orbNode)
            }

        }

1 个答案:

答案 0 :(得分:1)

positionDictionaryNSDictionary。您可以像使用Swift词典一样使用它 - 您不需要使用objectForKey

您应该使用if let和可选的强制转换来获取您想要的值,我认为这是NSDictionary的数组,因为您稍后再次使用objectForKey:< / p>

if let downcastedArray = positionDictionary["positions"] as? [NSDictionary] {

    for position in downcastedArray {
        let orbNode = Orb(textureAtlas: textureAtlas)
        let x = position["x"] as CGFloat
        let y = position["y"] as CGFloat
        orbNode.position = CGPointMake(x,y)
        foregroundNode!.addChild(orbNode)
    }
}

作为旁注,CGPointMake在Swift中不具有风格偏好。相反,请考虑使用CGPoint初始化程序:

orbNode.position = CGPoint(x: x, y: y)
相关问题