这不会编译:
我尝试过几种不同的东西;声明Dictionary的不同方法,更改其类型以匹配数据的嵌套。我还试着明确说我的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
}
}
答案 0 :(得分:19)
让我们来看看
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
}
答案 1 :(得分:3)
您可以按照以下步骤获取嵌套字典数据:
let imageData: NSDictionary = userInfo["picture"]?["data"]? as NSDictionary
let profilePic = imageData["url"] as? String
答案 2 :(得分:2)
func valueForCurrency(currency :String, exchange :String) -> Float? {
if let exchanges = response["current_rates"] as? Dictionary<String,Any> {
if let currencies = exchanges[exchange] as? Dictionary<String,Any> {
return currencies[currency] as? Float
}
}
return nil
}
答案 3 :(得分:1)
response
声明为:
var response = Dictionary<String,Any>()
因此编译器认为response["current_rates"]
将返回Any
。哪个可能是也可能不是下标可索引的东西。
您应该能够使用嵌套的Dictionaries定义您的类型,3个级别,最终您可以使用浮点数。您还需要使用可选链接进行钻取,因为字典可能有也可能没有该键的值,因此它的下标访问器返回一个可选链接。
var response = Dictionary<String,Dictionary<String,Dictionary<String,Float>>>()
// ... populate dictionaries
println(response["current_rates"]?["a"]?["b"]) // The float