kareem
kareem

Reputation: 933

ambiguous use of subscript swift 2.2

I have a lot of issues in my code with this error. Hopefully if someone can help me here than I can figure out the rest of the problems. I have updated to xcode 7.3 and running swift 2.2.

I have read that the compiler has been "more restrictive", and I have to tell it what the "intermediary" objects are. This is causing me some confusion and would love further explanation.

func getMessage(dictionary:NSDictionary)->String{

    var message = String()
    if let dict = dictionary["aps"] {
        if let message:String = dict["alert"] as? String {
            return message
        }
        else{
           message = ""
        }

    }
    return message   
}

enter image description here

Another example:

  for object in objects {
            let getDriver = object.objectForKey("driver")

            if let picture = getDriver!["thumbnailImage"] as? PFFile {
                self.profilePictures.append(picture)
            }
            self.requestsArray.append(object.objectId as String!)
        }

enter image description here

Upvotes: 1

Views: 3335

Answers (1)

vadian
vadian

Reputation: 285150

The type of a dictionary value is always AnyObject. Cast the type to something more specific for example

if let dict = dictionary["aps"] as? [String:AnyObject] {

then the compiler knows that key subscripting is valid and possible

The second example is similar: object is a dictionary and the compiler needs to know that the value for key driver is also a dictionary

if let getDriver = object.objectForKey("driver") as? [String:AnyObject] {
   if let picture = getDriver["thumbnailImage"] as? PFFile {
   ...

Upvotes: 6

Related Questions