kevingduck
kevingduck

Reputation: 531

Unclear "Type of expression is ambiguous without more context" error

I came back to my old XCode project after a few months and now I have lots of errors where I had none before, which I'm assuming has to do with an updated syntax.

Why am I seeing:

Type of expression is ambiguous without more context

for this block

@IBAction func submitUrl(sender: UIButton) {
    var app = UIApplication.sharedApplication().delegate as! AppDelegate
    //Error occurs in below declaration of studentDict
    var studentDict = ["latitude": self.latitude, "longitude": self.longitude, "firstName": app.firstName, "lastName": app.lastName, "mediaURL": urlField.text]
    var studentInfo = StudentInformation(data: studentDict as! [String : AnyObject])
    ParseClient.sharedInstance().postStudent(studentInfo, mapString: self.mapString){(success,data) in
        if(success){
            self.dismissViewControllerAnimated(true, completion: nil)
        }
        else{
            Shared.showError(self,errorString: data["ErrorString"] as! String)
        }

    }
}

I tried studentDict:NSArray and studentDict:Dictionary because I thought it just couldn't interpret the stuff in studentDict properly, but that did not help. What exactly is the error telling me that I'm missing?

Upvotes: 2

Views: 2821

Answers (2)

Sourabh Bhardwaj
Sourabh Bhardwaj

Reputation: 2604

In case if somebody still faces this kind of issue:

Golden rule of swift - You have to be clear about the type of your objects.

When you declare method which expects Array as parameter (without specifying the type of objects with in the array i.e. [String] or [MyModelObject] or [SKProduct]) and would like to use the parameter in the definition, you have two choices:

  • Either you specify the type of the object when try to use / access it. Below as example:

    for object in objects as! [SKProduct] { self.productsToPurchase.addObject(object) }

Here, objects is an array defined like this: var objects:NSArray?

  • Or revise the definition of your method and specify the type of objects. Below as example:

    func getMeProducts(products: [SKProduct]) { NSLog("Okay! Ready for purchase") }

In the latter case, the compiler won't allow you to send generic Array object. By generic I mean where you don't specify the type of objects array is holding on.

I hope this makes sense. If not, read the Golden rule again :)

Upvotes: 1

Nikolay Nankov
Nikolay Nankov

Reputation: 273

One or more of the values that you init with is probably optional and therefore can be nil. That's why you receive this error

var studentDict:[String:AnyObject?] = ["latitude": self.latitude, "longitude": self.longitude, "firstName": app.firstName, "lastName": app.lastName, "mediaURL": urlField.text]

Upvotes: 3

Related Questions