在swift中附加数组,遇到问题

时间:2015-02-04 17:33:04

标签: ios arrays swift cloudkit

我收到错误' AnyObject'没有名为'追加'的成员我试图发布到数组的结果。我不确定如何修复错误,因为我认为我的代码是正确的。有人可以帮我做出适当的调整吗?我的代码如下:

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

4 个答案:

答案 0 :(得分:1)

您从字典中获取aselfie。字典返回AnyObject类型的对象。由于您似乎有信心,因此Array可以将其投放到ArrayNSArray

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

答案 1 :(得分:1)

objectForKey的返回类型是AnyObject!

类型AnyObject没有名为append的方法。您需要将返回值强制转换为正确的类型。

此外,我不认为我看到你曾在data中输入了一个条目" selfie"。如果您希望它是一个数组,那么您需要调用data.setObject

答案 2 :(得分:0)

你应该将aselfie转换为数组然后调用它的append方法而不是它的下标

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

答案 3 :(得分:0)

我不认为aselfie.append[mySelfie]()是有效的Swift语法。它甚至编译?也许你的意思是aselfie.append(mySelfie)

另外,您如何知道aselfieArray?你应该施展它:

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