Search code examples
swiftxmlstring-conversion

Converting XML respons with numbers in String to Int Swift


Ive got an answer from an XML API that comes back to me as a String. I need it to be an int so that i can add it to another value in laters on. Ive tried to unwrap it and read it as an int but it didnt work. Ive also tried trimming blank spaces and then unwrap it but that didnt work either.

If i set the leading let value: Int it will give me an error saying that the value is not in the correct format.

What i have so far is this:

struct HydroData: Decodable {
    let value: String
    let textTranslationId: String?
    let titleTranslationId: String?
    let style: String?
}

struct HydroResult: Decodable {
    let HydroData: [HydroData]
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        calcIndex()
       
        let url = URL(string: "https://driftsdata.statnett.no/restapi/ProductionConsumption/GetLatestDetailedOverview")!
        let task = URLSession.shared.dataTask(with: url) { data, response, error in
            guard let data = data else {
                print("No data")
                return
            }
            do {
                let result = try JSONDecoder().decode(HydroResult.self, from: data)
                if let seDesc = result.HydroData.filter({ $0.titleTranslationId == "ProductionConsumption.HydroSEDesc" }).first {
                    
                    let hydroValue = seDesc.value
                    print(seDesc.value)
                    
                    
                } else {
                    print("Error: no value")
                }
            } catch {
                print(error.localizedDescription)
            }
        }
        task.resume()    }

    func calcIndex(){
        
       let newHydro = hydroValue + 1000
        print(newHydro)
}

}

Solution

  • You need to use initializer for Int that accepts String as parameter Int(). Also, I've fixed the issue you're gonna face when you try to use the Int(seDesc.value) because it contains a non-decimal-digit character. Here's the entire code:

    class ViewController: UIViewController {
    
        var hydroValue = 0
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            calcIndex()
    
            let url = URL(string: "https://driftsdata.statnett.no/restapi/ProductionConsumption/GetLatestDetailedOverview")!
            let task = URLSession.shared.dataTask(with: url) { data, response, error in
                guard let data = data else {
                    print("No data")
                    return
                }
                do {
                    let result = try JSONDecoder().decode(HydroResult.self, from: data)
                    if let seDesc = result.HydroData.filter({ $0.titleTranslationId == "ProductionConsumption.HydroSEDesc" }).first {
                        let value = seDesc.value.components(separatedBy: CharacterSet.decimalDigits.inverted).joined()
                        self.hydroValue = Int(value) ?? 0
                        print(value)
                        self.calcIndex()
                    } else {
                        print("Error: no value")
                    }
                } catch {
                    print(error.localizedDescription)
                }
            }
            task.resume()
        }
    
        func calcIndex(){
    
            let newHydro = hydroValue + 1000
            print(newHydro)
        }
    }