Int不符合协议'StringLiteralConvertible' [英] Int does not conform to protocol 'StringLiteralConvertible'

查看:105
本文介绍了Int不符合协议'StringLiteralConvertible'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在天气应用中解析json,但是遇到了我无法逾越的障碍。

Im trying to parse json in weather app, but have hit a snag that i cannot get past.

我确实收到错误消息,类型'int'确实不符合以下代码中的协议 StringLiteralConvertible。
我尝试过转换jsonResult [ main],但是确实给出了错误后缀的操作数应该具有可选类型,类型为AnyObject。我是否需要以某种方式下调Array,如果应该的话,应该如何做?
我为此进行了很多搜索,但在其他帖子中找不到任何帮助。代码如下。

I do get an error, "Type 'int' does not conform to Protocol 'StringLiteralConvertible'" in the following code. Ive tried casting the jsonResult["main"] but that does instead give the error "Operand of postfix should have optional type, type is AnyObject". Do i need to downcast the Array in some way and how, if so, should i do that? I´ve searched so much for this but could not find any help in other posts. Code as follows.

func updateWeatherInfo(latitude: CLLocationDegrees, longitude: CLLocationDegrees) {
    Alamofire.request(.GET, AlongRequest)
        .responseJSON { (_, _, JSON, error) in
            println(JSON)
            self.updateUISuccess(JSON as NSArray!)
    }
}

func updateUISuccess(jsonResult: NSArray) {
    self.loading.text = nil
    self.loadingIndicator.hidden = true
    self.loadingIndicator.stopAnimating()

    if let tempResult = ((jsonResult["main"] as NSArray)["temp"] as? Double)


推荐答案

如果您提供要解析的JSON,这将更容易给出明确的答案,但是错误消息是重新获得是很清楚的。

This would be easier to give a definitive answer to if you provide the JSON that you're trying to parse, but the error message you're getting is clear.

该错误是因为您试图访问声明为 NSArray 具有字符串下标的实例,在这一行中两次:

That error is because you're trying to access what you've declared as an NSArray instance with a string subscript, twice in this one line:

if let tempResult = ((jsonResult["main"] as NSArray)["temp"] as? Double)

jsonResult 被声明为 NSArray 参数,然后将 jsonResult [ main] 强制转换为 NSArray ,然后尝试使用 [ temp] 下标。这里的问题是 NSArray (和内置的Swift数组)仅使用基于整数的下标。错误是说在Swift编译器期望 Int 的地方,您提供了字符串文字。

jsonResult is declared as an NSArray parameter, and then you're casting jsonResult["main"] to NSArray before trying to subscript it with ["temp"]. The problem here is that NSArray (and built-in Swift arrays) only use integer-based subscripting. The error is saying that where the Swift compiler is expecting an Int, you've provided a string literal.

要解决此问题,您需要选择两个方向之一。如果您尝试访问的结构实际上具有这些字符串键,那么您应该使用 NSDictionary 而不是 NSArray 在两种情况下。如果不是,那是整数索引数组,则应该使用整数。

To fix this, you'll need to go in one of two directions. If the structure you're trying to access actually has these string keys, then you should be using NSDictionary instead of NSArray in both cases. If not, and it's an integer-index array, you should be using integers.

这篇关于Int不符合协议'StringLiteralConvertible'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆