-5
enter code here
@IBOutlet weak var textfield: UITextView!

@IBOutlet weak var label: UILabel!


var sentimentURL = "https://api.havenondemand.com/1/api/sync/analyzesentiment/v2?text=this+is+lethargic&apikey=e55bc0ff-70a5-4270-b464-aaaf3dfcc8de&text="
var sentimentResponse:NSDictionary!

func getSentiment() {
    var error:NSError?
    var encodedText = textfield.text.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)


    Get.JSON(url: sentimentURL+encodedText!) {
        (response) in
        self.sentimentResponse  = response

        DispatchQueue.main.async() {

            var agggregate = self.sentimentResponse["aggregate"]!["sentiment"]! as String
            self.label.text = agggregate

        }
    }
}

in this line " var agggregate = self.sentimentResponse["aggregate"]!["sentiment"]! as String" im getting error like Type 'Any' Has no Subscript Members.please help me in sorting this problem.thankyou in advance...

1 Answers1

0

You're using a function Get.JSON. You don't tell us what that is, or what data type the response will be.

I'm guessing that it is type Any, or perhaps [String:Any].

Your code self.sentimentResponse["aggregate"]!["sentiment"]! fails because the compiler does not know what kind of data self.sentimentResponse contains.

You could try casting it to the correct type:

guard let typedResponse  = response as? [String: [String:String]] else {return}
self.sentimentResponse = typedResponse
guard let aggregate = typedResponse["aggregate"] else {return}
guard let sentiment = aggregate["sentiment"] else {return}
DispatchQueue.main.async() {
   self.label.text = sentiment
}

(In the above code I'm using 3 separate guard statements to make debugging easier. You could use one guard statement with 3 separate let statements and accomplish the same thing)

Duncan C
  • 128,072
  • 22
  • 173
  • 272