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

前端之家收集整理的这篇文章主要介绍了尝试访问字典时出现Swift错误:“找不到成员”下标“前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这不会编译:

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

  1. import UIKit
  2.  
  3.  
  4. import Foundation
  5.  
  6. class CurrencyManager {
  7.  
  8. var response = Dictionary<String,Any>()
  9. var symbols = []
  10.  
  11.  
  12. struct Static {
  13. static var token : dispatch_once_t = 0
  14. static var instance : CurrencyManager?
  15. }
  16.  
  17. class var shared: CurrencyManager {
  18. dispatch_once(&Static.token) { Static.instance = CurrencyManager() }
  19. return Static.instance!
  20. }
  21.  
  22. init(){
  23. assert(Static.instance == nil,"Singleton already initialized!")
  24. getRates()
  25.  
  26. }
  27.  
  28.  
  29. func defaultCurrency() -> String {
  30.  
  31. let countryCode = NSLocale.currentLocale().objectForKey(NSLocaleCountryCode) as String
  32. let codesToCountries :Dictionary = [ "US":"USD" ]
  33.  
  34. if let localCurrency = codesToCountries[countryCode]{
  35. return localCurrency
  36. }
  37.  
  38. return "USD"
  39.  
  40. }
  41.  
  42. func updateBadgeCurrency() {
  43.  
  44. let chanCurr = defaultCurrency()
  45.  
  46. var currVal :Float = valueForCurrency(chanCurr,exchange: "Coinbase")!
  47.  
  48. UIApplication.sharedApplication().applicationIconBadgeNumber = Int(currVal)
  49.  
  50. }
  51.  
  52. func getRates() {
  53. //Network code here
  54. valueForCurrency("",exchange: "")
  55. }
  56.  
  57. func valueForCurrency(currency :String,exchange :String) -> Float? {
  58. return response["current_rates"][exchange][currency] as Float
  59. }
  60.  
  61.  
  62. }
我们来看看
  1. response["current_rates"][exchange][currency]

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

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

  1. var response = Dictionary<String,Dictionary<String,Float>>>()
  2.  
  3. func valueForCurrency(currency :String,exchange :String) -> Float? {
  4. return response["current_rates"]?[exchange]?[currency]
  5. }

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

  1. var response = Dictionary<String,Any>()
  2.  
  3. func valueForCurrency(currency :String,exchange :String) -> Float? {
  4. let exchanges = response["current_rates"] as? Dictionary<String,Any>
  5.  
  6. let currencies = exchanges?[exchange] as? Dictionary<String,Any>
  7.  
  8. return currencies?[currency] as? Float
  9. }

猜你在找的Swift相关文章