尝试访问字典时出现Swift错误:“找不到成员”下标“

尝试访问字典时出现Swift错误:“找不到成员”下标“,第1张

概述这不会编译: 我尝试了几件不同的事情;不同的声明Dictionary的方法,改变它的类型以匹配数据的嵌套.我也试图明确地说我的“任何”是一个集合,所以它可以被下标.没有骰子. import UIKitimport Foundationclass CurrencyManager { var response = Dictionary<String,Any>() var s 这不会编译:

我尝试了几件不同的事情;不同的声明Dictionary的方法,改变它的类型以匹配数据的嵌套.我也试图明确地说我的“任何”是一个集合,所以它可以被下标.没有骰子.

import UIKitimport Foundationclass CurrencyManager {    var response = Dictionary<String,Any>()    var symbols = []    struct Static {        static var token : dispatch_once_t = 0        static var instance : CurrencyManager?    }    class var shared: CurrencyManager {        dispatch_once(&Static.token) {  Static.instance = CurrencyManager() }        return Static.instance!    }    init(){        assert(Static.instance == nil,"Singleton already initialized!")        getRates()    }    func defaultCurrency() -> String {        let countryCode  = NSLocale.currentLocale().objectForKey(NSLocaleCountryCode) as String        let codesToCountrIEs :Dictionary = [ "US":"USD" ]        if let localCurrency = codesToCountrIEs[countryCode]{            return localCurrency        }        return "USD"    }    func updateBadgeCurrency() {        let chanCurr = defaultCurrency()        var currVal :float = valueForCurrency(chanCurr,exchange: "Coinbase")!        UIApplication.sharedApplication().applicationIconBadgeNumber = Int(currVal)    }    func getRates() {        //Network code here        valueForCurrency("",exchange: "")    }    func valueForCurrency(currency :String,exchange :String) -> float? {        return response["current_rates"][exchange][currency] as float    }}
我们来看看
response["current_rates"][exchange][currency]

响应声明为Dictionary< String,Any>(),所以在第一个下标之后,您尝试在类型为Any的对象上调用另外两个下标.

解决方案1.将响应类型更改为嵌套字典.请注意,我添加了问号,因为任何时候您访问一个字典项,您可以返回一个可选项.

var response = Dictionary<String,Dictionary<String,float>>>()func valueForCurrency(currency :String,exchange :String) -> float? {    return response["current_rates"]?[exchange]?[currency]}

解决方案2.解析时将每个级别转换为字典.确保仍然检查是否存在可选值.

var response = Dictionary<String,Any>()func valueForCurrency(currency :String,exchange :String) -> float? {    let exchanges = response["current_rates"] as? Dictionary<String,Any>    let currencIEs = exchanges?[exchange] as? Dictionary<String,Any>    return currencIEs?[currency] as? float}
总结

以上是内存溢出为你收集整理的尝试访问字典时出现Swift错误:“找不到成员”下标“全部内容,希望文章能够帮你解决尝试访问字典时出现Swift错误:“找不到成员”下标“所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1045525.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-24
下一篇 2022-05-24

发表评论

登录后才能评论

评论列表(0条)

保存