将 XML 将 String 中的数字响应为 Int Swift

Converting XML respons with numbers in String to Int Swift

我从 XML API 那里得到了答案,它以字符串的形式返回给我。我需要它是一个 int 以便我可以在以后将它添加到另一个值。我试图打开它并将它作为一个 int 来读取,但它没有用。我也试过修剪空格然后打开它,但那也没有用。

如果我设置前导 let value: Int,它会给我一个错误,指出该值的格式不正确。

我目前的情况是这样的:

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({ [=12=].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)
}

}

您需要为接受 String 作为参数 Int() 的 Int 使用初始化程序。此外,我还解决了您在尝试使用 Int(seDesc.value) 时会遇到的问题,因为它包含非十进制数字字符。这是完整的代码:

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({ [=10=].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)
    }
}