Swift转换类型

时间:2016-06-05 20:55:41

标签: json swift

我需要解析JSON文件。这是我的getJSON函数

public var shops: NSArray = []
public func getShop() {    
let url = NSURL (string: "http://urltojson.com")    
let data = NSData (contentsOfURL: url!)    
shops = try! NSJSONSerialization.JSONObjectWithData(data!,options: .AllowFragments) as! NSArray        
}

以下是我从JSON获取数据的方法

override func viewDidLoad() {
    let test = shops ["Titile"] as? String
    print(test)
}

问题是当我运行我的代码时它会向我显示错误"无法转换类型' String'期望参数类型Int" 所以,如果我在let test = shops ["Titile"]中为任何Int更改[" Titile"],例如[8] let test = shops [8] as? String它有效。 我做错了什么?

1 个答案:

答案 0 :(得分:1)

看起来你的变量“shops”是一个数组,它将索引作为整数而不是将字符串作为字符串的字典。

//here shops is an array of strings
var shops:[String] = ["dog","cat","pig","cow"]
//shops[2] is equal to "pig"

//here shops is a dictionary of string keys and string values
var shops:[String:String] = ["animal1":"dog","animal2":"cat","animal3":"pig","animal4":"cow"]
//shops["animal2"] is equal to "cat"