简体   繁体   中英

“Type'Program' does not conform to protocol 'Any Object'”

I updated xcode and now I have error in my project and I dont have idea what to do with it.

struct Program {
    let name : String
    let url : String
}

self.arrayOfPrograms = [Program(name: "First", url: "http://1.com"), Program(name: "Second", url: "http://2.com"), Program(name: "Third", url: "http://2.com")]

and I'm getting error "Type'Program' does not conform to protocol 'Any Object'"

As reported in the documentation :

AnyObject can represent an instance of any class type.

A struct is not a class, so it cannot be cast to AnyObject

You should either:

  • turn Program into a class
  • define your array as Array<Any>
  • if your array is supposed to hold instances of Program only, declare it as Array<Program>

Needless to say, the last is the best solution, whereas the first is the one I wouldn't recommend because it requires you to make design changes (there's a reason why you declared it as a value type and not a reference type).

Side note: arrays and dictionaries can be cast to AnyObject because they are automatically bridged respectively to NSArray and NSDictionary , which are classes.

check this link you got your answare I recently wrapped my head around something that I have found very strange in Swift. Swift provides two high level protocols called Any and AnyObject. Any can be used for both value types (like structs) and reference types (classes) while AnyObject can only be used for classes.

enter link description here

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