在初始化之前使用结构

Using Structure before Initialization

我在初始化汇率结构时遇到了问题。在方法 getRates 中,我一直在尝试实现字典键/值逻辑以将汇率复制到有序数组中。我收到错误“初始化前使用的变量 'moneyRates'”。我尝试添加一个成员初始化器,但不确定如何初始化速率数组。我也一直想知道是否应该将 MoneyRates 的实例移动到 class 的顶部而不是在 getRates 方法中。

var currCode: [String] = ["usd", "afn", "all", "dzd", "amd", "ang", "aoa", "ars", "aud", "awg", "azn",
                          
    /* b */ "bsd", "bhd", "bdt", "bbd", "byr", "bzd", "bmd", "btn", "bob", "bam", "bwp", "brl", "bnd", "bgn", "bif",
    
    /* c */ "cad", "khr", "cve", "xcd", "kyd", "xaf", "xof", "xpf", "clf", "clp", "cnh", "cny", "cop", "kmf", "cdf", "crc", "hrk", "cup", "czk"]




struct MoneyRates {
        let date: String
        let base: String
        let rates: [String: Double]
    }
    
    class CurrencyRates: ObservableObject {
        
        @Published var rateArray = [Double] ()
        
        init() {
            
            if UserDefaults.standard.array(forKey: "rates") != nil {
                rateArray = UserDefaults.standard.array(forKey: "rates") as! [Double]
                
            } else {
                rateArray = [Double] (repeating: 0.0, count: 170)
                UserDefaults.standard.set(self.rateArray, forKey: "rates")
            }
        }
        
        // retrieve exchange rates for all 150+ countries from internet and save to rateArray
        func updateRates(baseCur: String) {
            
            print("doing update")
            
            let baseUrl = "https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/"
            let requestType = ".json"
            
            guard let url = URL(string: baseUrl + baseCur + requestType) else {
                print("Invalid URL")
                return
            }
            let request = URLRequest(url: url)
            
            URLSession.shared.dataTask(with: request) { data, response, error in
                
                if let data = data {
                    do {
                        let result = try JSONSerialization.jsonObject(with: data) as! [String:Any]
                        
                        var keys = Array(result.keys)
                        if let dateIndex = keys.firstIndex(of: "date"),
                           let date = result[keys[dateIndex]] as? String, keys.count == 2 {
                            keys.remove(at: dateIndex)
                            let base = keys.first!
                            print("base = \(base)")
                            print("date = \(date)")
                            let rates = MoneyRates(date: date, base: base, rates: result[base] as! [String:Double])
                            print(rates)
                            
                            self.getRates(rates: rates, baseCur: baseCur)  
                        }
                    } catch {
                        print(error)
                    }
                }
            }.resume()
        }
        
        
        // copy rates from MoneyRates to rateArray
        func getRates (rates: MoneyRates, baseCur: String) -> () {
            
            var moneyRates: MoneyRates
            var currencyCode: String = ""
        
            // loop through all available currencies
            // the rates are stored in the same order as currCode
            for index in 0..<currCode.count {
                currencyCode = currCode[index]
                
                // special handling for base currency
                if currencyCode == baseCur {
                    rateArray[index] = 1.0000
                    
                } else {
                    print(currencyCode)
                    
                    if moneyRates.rates[currencyCode] != nil {      // error here
                let unwrapped = (moneyRates.rates[currencyCode]!)   // and here (same)
                print( unwrapped)
                rateArray[index] = 1.0 / unwrapped // want inverse exchange rate
            }
        }
        UserDefaults.standard.set(self.rateArray, forKey: "rates")
     }  
 }

}

您收到的错误是因为您声明了变量“moneyRates” 但你没有将它实例化为某物。

var moneyRates: MoneyRates

换句话说,“moneyRates”中没有任何内容, 但你正试图从中得到一些东西:

if moneyRates.rates[currencyCode] != nil {
   ...
}  

所以用一些数据填充“moneyRates”。