gpt4 book ai didi

尝试访问字典时出现 Swift 错误 : `Could not find member ' subscript'`

转载 作者:IT王子 更新时间:2023-10-29 05:20:58 26 4
gpt4 key购买 nike

这不会编译: enter image description here我尝试了几种不同的方法;声明字典的不同方式,更改其类型以匹配数据的嵌套性。我还尝试明确地说我的 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
}


}

最佳答案

我们来看看

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

response声明为 Dictionary<String,Any>() ,因此在第一个下标之后,您尝试在 Any 类型的对象上调用另外两个下标。

解决方案 1. 将响应类型更改为嵌套字典。请注意,我添加了问号,因为无论何时您访问字典项目,您都会得到一个可选的。

var response = Dictionary<String,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 错误 : `Could not find member ' subscript'`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24128536/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com