简体   繁体   中英

iOS SWIFT - File Archive - Argument Type “[String?]” : does not conform to expected type'AnyObject'

I am trying to write into an Archive and getting this error .

My tech stack is : XCode 7.1 Beta and SWIFT .Appreciate if any of you could share the exact code to fix this issue. Thanks in advance.

Argument Type "[String?]" : does not conform to expected type'AnyObject'

@IBAction func saveArch(sender: AnyObject) {

    var contactArray = [name.text, address.text, phone.text]
    NSKeyedArchiver.archiveRootObject(contactArray,
        toFile: dataFilePath!)

}

Thanks

Array is not of type AnyObject

You should try

NSKeyedArchiver.archiveRootObject(NSArray(array: contactArray),
    toFile: dataFilePath!)

You are sending a swift [] object that does not conform to AnyObject since arrays and object are different things in swift.

NSArray cannot contains optionals

You also have a problem with optionals: one or all of your .text is of type String? (therefor it might be nil).

If you are positive none of this field is nil, you can use

var contactArray = [name.text!, address.text!, phone.text!]

Or change the declaration.

If you are not sure, you should do something like

var contactArray = [String]()

for element in [name.text, address.text, phone.text] where element != nil {
    array.append(element!)
}
NSKeyedArchiver.archiveRootObject(NSArray(array: contactArray),
    toFile: dataFilePath!)

This way you only add non nil elements to the contactArray By the way, Xcode 7.1 is out. No need to use the beta anymore

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM