0
init?(plistRepresentation : AnyObject){
            switch plistRepresentation{
            case "viewing":
                self = .viewing
    }
}

The above code generates "Expression pattern of type 'String' cannot match values of type 'AnyObject'" error. But the moment I add "as Sttring"

init?(plistRepresentation : AnyObject){
                switch plistRepresentation{
                case "viewing" as String:
                    self = .viewing
        }
    }

the error goes away.. Can anyone explains to me how this works? It looks kinda confusing to me.

Thanks

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
progammingBeignner
  • 936
  • 1
  • 8
  • 19

1 Answers1

1

AnyObject is a generalise type that includes all type of object type like array, dictionary, set, string, etc.

AnyObject refers to any instance of a class, and is equivalent to id in Objective-C. It's useful when you specifically want to work with a reference type, because it won't allow any of Swift's structs or enums to be used.

Swift's switch want a specific type to match the case that's the reason when you put as String the error goes away.

More detail on AnyObject can be found here

Mahendra
  • 8,448
  • 3
  • 33
  • 56
  • I am more curious of the switch statement. I read the article you have given. So switch case always need a concrete time? But isn;t compile aware of the fact that I am using a String type? Because the error already states so? – progammingBeignner Nov 02 '18 at 09:14
  • @progammingBeignner since you are pattern matching on an object of type `AnyObject`, you cannot simply try pattern matching literal values of a class conforming to `AnyObject`. You need to explicitly cast to the concrete type (`String` in your case) to let the compiler know that before pattern matching the value, it should pattern match the type casting as well. – Dávid Pásztor Nov 02 '18 at 09:36
  • @DávidPásztor ok, that sounds reasonable to me. Thanks! – progammingBeignner Nov 02 '18 at 09:39