我正在建造一些东西,在斯威夫特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。你可以像快速字典一样使用它-你不需要使用objectForKey
您应该只使用if let和可选的casting来获得所需的值,我认为这是一个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)
    }
}

另外,Swift在风格上不倾向于使用CGPointMake。相反,请考虑使用CGPoint初始值设定项:
orbNode.position = CGPoint(x: x, y: y)

关于swift - 没有名为“下标”的成员,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29581068/

10-15 15:13