user4777675
user4777675

Reputation:

Does not have a member named 'subscript'

I'm building something and it all worked fine until Swift 1.2 came out. I made some changes but still have one line of code that is playing nice. I don't understand why this is breaking:

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

it gives me an error:

'(AnyObject) -> AnyObject?' does not have a member named 'subscript'

I also tried using this:

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

but then I get an error saying:

Operand of postfix '?' should have an optional type; type is '(AnyObject) -> AnyObject?'

I'm really confused...can anyone help?

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

        }

Upvotes: 1

Views: 785

Answers (1)

Aaron Brager
Aaron Brager

Reputation: 66302

positionDictionary is an NSDictionary. You can use it just like a Swift dictionary - you don't need to use objectForKey.

You should just use if let and optional casting to get the value you want, which I think is an array of NSDictionary since you're using objectForKey again later:

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

As a side note, CGPointMake is not stylistically preferred in Swift. Instead, consider using the CGPoint initializer:

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

Upvotes: 1

Related Questions