加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 05:42:02 所属栏目:百科 来源:网络整理
导读:这不会编译: 我尝试了几件不同的事情;不同的声明Dictionary的方法,改变它的类型以匹配数据的嵌套.我也试图明确地说我的“任何”是一个集合,所以它可以被下标.没有骰子. import UIKitimport Foundationclass CurrencyManager { var response = DictionaryStr
这不会编译:

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

import UIKit


import Foundation

class 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
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读