Andy Dewan
Andy Dewan

Reputation: 245

Appending an array in swift, having problems

I am getting the error 'AnyObject' does not have a member named 'append' for results that I am trying to post to an array. I'm not sure how to fix the error, as I thought my code was correct. Can someone help me make the proper adjustments? My code is as follows:

import CloudKit
import UIKit
import Foundation

class Items {
    var theSelfie: [String]

    init(record: CKRecord) {
        println("init")
        var record: CKRecord
        var iama: String
        var youarea: String
        var image: CKAsset? // tried also initializing the CKAsset separately
        var postPic: UIImage?

        let database = CKContainer.defaultContainer().publicCloudDatabase
        let container = CKContainer.defaultContainer()
        let publicDB = container.publicCloudDatabase
        let data = CKRecord(recordType: "theUsers")

        var predicate = NSPredicate(value: true)
        let myQuery = CKQuery(recordType: "theUsers", predicate: predicate)

        var mySelfie = theSelfie

        publicDB.performQuery(myQuery, inZoneWithID: nil) { results, error in
            if error != nil {
                println(error)
            } else {
                for record in results{
                    let aselfie = data.objectForKey("selfie")
                        aselfie.append[mySelfie]()
                        return ()
                    }        
                }
            }
        }
    }
}

Upvotes: 0

Views: 465

Answers (4)

Zell B.
Zell B.

Reputation: 10286

You should cast aselfie to array then call its append method not its subscript

if let aselfie = data.objectForKey("selfie") as? [AnyObject] // if aselfie is supposed to hold object of single type case it as [ObjcetsToHold]
                    aselfie.append(mySelfie)
                    return ()
                } 

Upvotes: 0

Marcos Crispino
Marcos Crispino

Reputation: 8218

I don't think that aselfie.append[mySelfie]() is valid Swift syntax. Does it even compile? Maybe you meant aselfie.append(mySelfie)?

Also, how do you know that aselfie is an Array? You should cast it:

let aselfie = data.objectForKey("selfie") as? Array<Whatever>
    aselfie.append[mySelfie]()
    return ()
} 

Upvotes: 0

Michael Welch
Michael Welch

Reputation: 1784

The return type of objectForKey is AnyObject!

The type AnyObject doesn't have a method named append. You'll need to cast the return value to the correct type.

In addition, I don't think I see you ever put an entry in data with key "selfie". If you want it to be an array then somewhere you need to call data.setObject

Upvotes: 1

orkoden
orkoden

Reputation: 19996

You're getting aselfie from a dictionary. The dictionary returns objects of type AnyObject. Since you seem confident, that's it's an Array you can cast it to Array or NSArray.

let aselfie = data.objectForKey("selfie") as Array

Upvotes: 1

Related Questions