【问题标题】:Does not have a member named 'subscript'没有名为“下标”的成员
【发布时间】:2015-04-11 17:49:00
【问题描述】:

我正在构建一些东西,在 Swift 1.2 发布之前一切正常。我做了一些更改,但仍然有一行代码运行良好。我不明白为什么会这样:

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

它给了我一个错误:

'(AnyObject) -> AnyObject?'没有名为“下标”的成员

我也试过用这个:

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)
            }

        }

【问题讨论】:

    标签: swift


    【解决方案1】:

    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 中不是风格上的首选。相反,请考虑使用 CGPoint 初始化器:

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

    【讨论】:

    • “另外,你不应该在 Swift 中使用 CGPointMake” 在我看来这有点远。 :)
    • @matt 谢谢,我更新了一个注释,这只是一个风格建议。
    • 为什么在 Swift 中使用 CGPointMake 在风格上不是首选?谢谢。
    • @Unheilig 它看起来不像Swift Initializer。它也只接受 CGFloat 参数,不像普通的初始化器,它可以接受其他类型。
    • 感谢您的帮助。它解决了这个问题..但现在我有了另一个初始化器。
    猜你喜欢
    • 1970-01-01
    • 2014-12-17
    • 1970-01-01
    • 2015-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多