在初始化之前使用结构

Posted

技术标签:

【中文标题】在初始化之前使用结构【英文标题】:Using Structure before Initialization 【发布时间】:2021-06-09 23:38:36 【问题描述】:

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

【问题讨论】:

【参考方案1】:

你得到的错误是因为你声明了变量“moneyRates” 但你没有将它实例化为某个东西。

var moneyRates: MoneyRates

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

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

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

【讨论】:

以上是关于在初始化之前使用结构的主要内容,如果未能解决你的问题,请参考以下文章

C语言中,使用一个结构体之前,要用memset把各个位清零???

未初始化的 C++ 结构的行为

出现错误:在初始化所有存储的属性之前,方法调用“getliveData”中使用了自我

两个结构初始化之间的区别

Spring:在创建任何 bean 之前初始化属性

如何修复错误:@FetchRequest 中的“属性初始化程序在”自我“可用”之前运行