Swift - 从[SKNode]转换为不相关的类型'String'始终失败

时间:2015-05-18 07:17:15

标签: swift sknode

我是快速语言的初学者,目前我正在开发一些应用程序(游戏)。 但是我在将AnyObject转换为String时遇到问题,或者总是发出警告“从[SKNode]转换为无关类型'String'总是失败”

这是我的代码

var facets = [AnyObject]()
init () {
        facets = [
            [
                "id": "1",
                "lang": ["id": "Memori", "en": "Memory"]
            ],
            [
                "id": "2",
                "lang": ["id": "Kecepatan Berpikir", "en": "Speed"]
            ],
            [
                "id": "3",
                "lang": ["id": "Fungsi Eksekutif", "en": "Control"]
            ],
            [
                "id": "4",
                "lang": ["id": "Konsentrasi", "en": "Attention"]
            ],
            [
                "id": "5",
                "lang": ["id": "Pemecahan Masalah", "en": "Problem Solving"]
            ]
        ]
    }

func findFacetUsingId(id: String?) -> String? {
        if let id = id {
            for value in facets {
                var facet_id: String = value["id"] as! String
                if id == facet_id {
                    var names: Dictionary<String, String> = value["lang"] as! Dictionary<String, String>
                    return names[Lang.ID]
                }
            }
        }

        return nil
    }

这是截图, enter image description here

顺便说一句,我在使用这段代码时取得了成功

var facet_id: String = value.objectForKey("id") as! String

而不是

var facet_id: String = value["id"] as! String

但是App很慢(非常慢)

提前谢谢

1 个答案:

答案 0 :(得分:0)

实际上,如果您只做一点改动,您的代码就会起作用:

func findFacetUsingId(id: String?) -> String? {
  if let id = id {
    for value in facets {
      var facet_id: String = value["id"] as! String
      if id == facet_id {
        var names: Dictionary<String, String> = value["lang"] as! Dictionary<String, String>
        return names["id"]
      }
    }
  }
return nil
}