Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
尝试访问字典时出现Swift错误:`找不到成员';下标'`_Swift - Fatal编程技术网

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

尝试访问字典时出现Swift错误:`找不到成员';下标'`,swift,Swift,这不会编译: 我试过几种不同的方法;声明字典的不同方式,更改其类型以匹配数据的嵌套性。我还试图明确地说我的Any是一个集合,因此可以订阅它。没有骰子 import UIKit import Foundation class CurrencyManager { var response = Dictionary<String,Any>() var symbols = [] struct Static { static var toke

这不会编译: 我试过几种不同的方法;声明字典的不同方式,更改其类型以匹配数据的嵌套性。我还试图明确地说我的
Any
是一个集合,因此可以订阅它。没有骰子

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
    }


}
导入UIKit
进口基金会
类货币管理器{
var response=Dictionary()
变量符号=[]
结构静态{
静态变量令牌:分派\u一次\u t=0
静态变量实例:CurrencyManager?
}
类var共享:CurrencyManager{
dispatch_once(&Static.token){Static.instance=CurrencyManager()}
返回Static.instance!
}
init(){
断言(Static.instance==nil,“Singleton已初始化!”)
getRates()
}
func defaultCurrency()->字符串{
让countryCode=NSLocale.currentLocale().objectForKey(NSLocaleCountryCode)作为字符串
让codesToCountries:Dictionary=[“美国”:“美元”]
如果让localCurrency=codesToCountries[countryCode]{
返回本地货币
}
返回“美元”
}
func updateBadgeCurrency(){
设chanCurr=defaultCurrency()
var currVal:Float=valueForCurrency(chanCurr,exchange:“Coinbase”)!
UIApplication.sharedApplication()
}
func getRates(){
//这里是网络代码
valueForCurrency(“,exchange:”)
}
func valueForCurrency(货币:字符串,交易所:字符串)->浮动{
以浮动形式返回响应[“当前汇率”][汇率][货币]
}
}
让我们看看

response["current_rates"][exchange][currency]

response
声明为
Dictionary()
,因此在第一个下标之后,您可以尝试调用任意类型对象上的另外两个下标

解决方案1。将响应类型更改为嵌套字典。请注意,我添加了问号,因为无论何时访问字典项,都会返回可选项

var response = Dictionary<String,Dictionary<String,Dictionary<String, Float>>>()

func valueForCurrency(currency :String, exchange :String) -> Float? {
    return response["current_rates"]?[exchange]?[currency]
}
var response = Dictionary<String,Dictionary<String,Dictionary<String,Float>>>()
// ... populate dictionaries
println(response["current_rates"]?["a"]?["b"]) // The float
var response=Dictionary()
func valueForCurrency(货币:字符串,交易所:字符串)->浮动?{
返回响应[“当前汇率”]?[汇率]?[货币]
}
解决方案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
}
var response=Dictionary()
func valueForCurrency(货币:字符串,交易所:字符串)->浮动?{
让交换=响应[“当前利率”]作为字典
让货币=交换?[交换]作为字典
返回货币?[货币]作为浮动货币
}

响应
声明如下:

var response = Dictionary<String,Any>()
func valueForCurrency(货币:字符串,交易所:字符串)->浮动?{
如果let exchanges=response[“current_rates”]as?字典{
如果让货币=交换[交换]为?字典{
以浮动形式返回货币[货币]
}
}
归零
}

您可以通过以下步骤获取嵌套字典数据:

let imageData: NSDictionary = userInfo["picture"]?["data"]? as NSDictionary
let profilePic = imageData["url"] as? String

有什么理由不起作用吗
let exchanges=response[“current_rates”]作为字典?
I get“无法找到接受提供参数的下标的重载”我添加了第二个解决方案。要使用该方法,您只需要在“as”后面加问号,而不是在“Dictionary”后面加问号,这样做没有硬编码嵌套类型吗?(即我对Alex答案的评论)只需添加元素类型:
let symbols=response[“symbols”]as?数组
问题在于,并非整个层次结构中的所有对象都遵循这些泛型。某个地方可能有一个数组,我不想在这段代码中硬编码JSON的整个解释。然后你需要在运行时检查类型并强制转换。问题是,我知道我想要的元素的具体类型,我想忽略其他元素。如果我访问[“当前费率”],我知道我总能得到一本字典。
let imageData: NSDictionary = userInfo["picture"]?["data"]? as NSDictionary
let profilePic = imageData["url"] as? String