Search code examples
iosswiftintegerdoublealamofire

Sum of Int from stringValue


I am parsing data from mysql into my IOS swift app using Alamofire, the data are Integers, and I am fetching them into text fields then I will do some calculations on them, I loaded the data Successful but the issue that they cann't be assigned to the text fields!

func getIcomeData() {
    start()
    let url = URLs.income
    AF.request(url).validate().responseJSON { response in
            switch response.result {
            case .success:
                print("Validation Successful)")

                if let json = response.data {
                    do{
                        let jsonData = try JSON(data: json)
                        let dataarray = jsonData.arrayValue
                        print("DATA PARSED: \(jsonData)")
                        for itemDict in dataarray{

                            let int1 = itemDict["Base-Pay-Monthly"].intValue
                            **self.BPMTXT.text = itemDict["Base-Pay-Monthly"].intValue**
                            
                            let int2 = itemDict["Overtime"].intValue
                            **self.OTTXT.text = itemDict["Overtime"].intValue**
                                    
                                                       
                            let int6 = itemDict["Others"].intValue
                            **self.OthersTXT.text = itemDict["Others"].intValue**
                            
                            let totalIncome = [int1, int2, int3, int4, int5, int6]
                            let sum = totalIncome.reduce(0, +)
                            //self.NetPayLabel.text = String(sum)
                            self.NetPay = Double(sum)
                            
                            
                        }
                        self.stop()
                    }
                    catch {
                        print("JSON Error", error)
                    }
                }
            case .failure(let error):
                print(error)
            }
        }

}

I am getting this error Cannot assign value of type 'Int' to type 'String' on the bolded lines


Solution

  • The error message is very clear.

    self.BPMTXT.text is String. itemDict["Base-Pay-Monthly"].intValue is Int. Cannot assign value of type 'Int' to type 'String'

    Try the following modifications.

    self.BPMTXT.text = "\(itemDict["Base-Pay-Monthly"].intValue)"
    
    self.OTTXT.text = "\(itemDict["Overtime"].intValue)"
    
    self.OthersTXT.text = "\(itemDict["Others"].intValue)"