Swift 没有名为'的成员;下标';

Swift 没有名为'的成员;下标';,swift,Swift,我正在建造一些东西,在Swift 1.2问世之前,一切都很顺利。我做了一些更改,但仍有一行代码运行良好。我不明白为什么会这样: let swiftArray = positionDictionary.objectForKey["positions"] as? [AnyObject] 这给了我一个错误: “(AnyObject)->AnyObject”没有名为“subscript”的成员 我也试着用这个: let swiftArray = positionDictionary.objectFor

我正在建造一些东西,在Swift 1.2问世之前,一切都很顺利。我做了一些更改,但仍有一行代码运行良好。我不明白为什么会这样:

let swiftArray = positionDictionary.objectForKey["positions"] as? [AnyObject]
这给了我一个错误:

“(AnyObject)->AnyObject”没有名为“subscript”的成员

我也试着用这个:

let swiftArray = positionDictionary.objectForKey?["positions"] as? [AnyObject]
但是我得到一个错误,说:

后缀“?”的操作数应具有可选类型;类型为“(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)
            }

        }

positionDictionary
是一个
NSDictionary
。您可以像使用Swift字典一样使用它—您不需要使用
objectForKey

您应该只使用
if let
和可选强制转换来获得所需的值,我认为这是一个
NSDictionary
数组,因为您稍后再次使用
objectForKey

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中不是首选的样式。相反,考虑使用<代码> CGPooP初始化器:

orbNode.position = CGPoint(x: x, y: y)

“另外,您不应该在Swift中使用CGPointMake”,这在我看来有点过分@matt谢谢,我更新了一条说明,这只是一个风格上的建议。为什么在Swift中使用
CGPointMake
?谢谢你。@Unheilig它看起来不像是一个。它也只接受
CGFloat
参数,不像普通的初始值设定项,它可以接受其他类型。谢谢你的帮助。它解决了这个问题…但现在我有另一个与初始化。