简体   繁体   English

老雨燕到雨燕3

[英]Old Swift to Swift 3

A while back I created a function to take a json and print it to the terminal. 不久前,我创建了一个函数来获取json并将其打印到终端。 It worked perfectly but it was two years ago so when I have copied it in for my latest project it is full of errors :/ I have resolved most of them but I still have two outstanding issues as follows: 它运行良好,但是是两年前的,所以当我将其复制到我的最新项目中时,它充满了错误:/我已经解决了大多数错误,但是仍然存在两个突出的问题,如下所示:

var arr = JSONSerialization.JSONObjectWithData(data!, options: nil, error: nil) as! NSArray

The above line complains about "Extra Argument 'error' in call. 上一行抱怨呼叫中存在“额外参数错误”。

for var i = 0 ; i < (arr as NSArray).count ; i += 1

The above line says "C-Style for statement has been removed in swift 3" 上面的代码行说:“ C-Style for statement已在迅速3中删除”

Any help on resolving these two would be great. 解决这两个问题的任何帮助都会很棒。

Full Function Code Below: 完整功能代码如下:

func jsonParsing()
{

    let prefs:UserDefaults = UserDefaults.standard
    var webaddress = prefs.value(forKey: "WEBADDRESS") as! String


    let url2 = URL(string: webaddress + "straightred/jsonfixture/")

    let data = try? Data(contentsOf: url2!)

    var arr = JSONSerialization.JSONObjectWithData(data!, options: nil, error: nil) as! NSArray

    arrDict = []

    for var i = 0 ; i < (arr as NSArray).count ; i += 1
    {
        arrDict.addObject((arr as NSArray) .objectAtIndex(i))
    }

    print(arrDict);

}

First of all, do not use NSArray in Swift , use Swift native collection types. 首先, 不要在Swift中使用NSArray ,而应使用Swift本机集合类型。

Second of all, do not load data synchronously from a remote URL , use URLSession 其次, 不要从远程URL同步加载数据 ,请使用URLSession

Third of all, you don't need the loop, just assign the received array to arrDict 第三,您不需要循环,只需将接收到的数组分配给arrDict

  • Declare arrDict as Swift array of dictionaries arrDict声明为Swift的字典数组

     var arrDict = [[String:Any]]() 
  • This code uses the proper method of UserDefaults and a do - catch block, the options parameter of jsonObject(with can be omitted. 这段代码使用UserDefaults的正确方法和do - catch块,以及jsonObject(withoptions参数可以省略。

     func jsonParsing() { let prefs = UserDefaults.standard let webaddress = prefs.string(forKey: "WEBADDRESS")! let url2 = URL(string: webaddress + "straightred/jsonfixture/")! let task = URLSession.shared.dataTask(with: url2) { [unowned self] (data, response, error) in if let error = error { print(error) return } do { let arr = try JSONSerialization.jsonObject(with:data!) as! [[String:Any]] self.arrDict = arr print(self.arrDict) } catch { print(error) } } task.resume() } 

JSONSerialization no longer takes an error reference as aparameter, now it throws exception JSONSerialization不再将错误引用作为参数,现在会引发异常

var arr : Array<AnyObject> = try JSONSerialization.jsonObject(with: data, options: nil)

As for the loop, the C-style loops were completely removed in Swift 3 so use 至于循环,C型循环在Swift 3中已完全删除,因此请使用

for object in arr {
    // do stuff
}

or 要么

for i in 0<..arr.count {
    // do stuff
}

For the first one you need to add do try catch 对于第一个,您需要添加do try catch

    do {
    var arr : Array<AnyObject> = JSONSerialization.jsonObject(with: data!)) as! NSArray
    // do your works
    } catch {
    print("Got error: \(error)")
}

For the second one you need to have your for loops in the following way 对于第二个,您需要通过以下方式进行for循环

for i in 0..<arr.count {
  //do your stuff here
}

For loop format: 对于循环格式:

for i in 0..<arr.count {
    ...code here...
} 

Swift 3.1 斯威夫特3.1

for JSON serialization try like this: 对于JSON序列化,请尝试如下操作:

 do {
       var arr = try  JSONSerialization.jsonObject(with: data, options: []) as! NSArray

   } catch {

  }

for Loop syntax use like this for循环语法使用像这样

 for i in 0..<arr.count {
         // Do your stuff       
 }

This is your full function in valid Swift 3 syntax. 这是有效的Swift 3语法的全部功能。

Be aware that JSONSerialization.jsonObject can now throw. 请注意, JSONSerialization.jsonObject现在可以抛出。 You can just use the for element in collection syntax, you don't need to specify the indexes yourself and the C style for loop has been removed from Swift 3, if you really need a C style for loop, you have to use stride . 您可以for element in collection语法中使用for element in collection无需自己指定索引,并且Swift 3中的C样式已从Swift 3中删除,如果您确实需要C样式的for循环,则必须使用stride

Using NSArray is discouraged in Swift, if you really want to use non-explicit types, use Array<Any> , but when possible use explicit types. 在Swift中不建议使用NSArray ,如果您确实想使用非显式类型,请使用Array<Any> ,但在可能的情况下,请使用显式类型。

Also make sure that you handle the optional unwrapping correctly and when using force unwrapping/force casting, you won't get a runtime error. 还要确保正确处理可选的展开,并且在使用强制展开/强制转换时,不会出现运行时错误。

func jsonParsing(){

    let prefs:UserDefaults = UserDefaults.standard
    var webaddress = prefs.value(forKey: "WEBADDRESS") as! String


    let url2 = URL(string: webaddress + "straightred/jsonfixture/")

    let data = try? Data(contentsOf: url2!)

    var arr = (try? JSONSerialization.jsonObject(with: data!)) as! NSArray

    var arrDict = [Any]()

    for current in arr {
        arrDict.append(current)
    }

    print(arrDict)

}
func jsonParsing()
{

let prefs:UserDefaults = UserDefaults.standard
var webaddress = prefs.value(forKey: "WEBADDRESS") as! String


let url2 = URL(string: webaddress + "straightred/jsonfixture/")

let data = try? Data(contentsOf: url2!)

var arr = try JSONSerialization.jsonObject(with: data!) as! [Any] // if Array of any type, if array of dictionaries cast it to [[String:Any]]

arrDict = []

for value in arr { // instead of iterating over your array you can simply copy it to arrDict. I added for loop for your refernce.
   arrDict.addObject(name) 
 } 
print(arrDict);

}

JSON serialization methods have been updated. JSON序列化方法已更新。 C style for loops are deprecated use enumeration to enumerate over your complete array. 不建议使用C样式的循环,而应使用枚举来枚举整个数组。 I wont support using Objective-C classes in your Swift class. 我不支持在您的Swift类中使用Objective-C类。 Dont caste your arrays to NSArray or NDDictionary. 不要将数组强制转换为NSArray或NDDictionary。

In Swift 3, try this code for son parsing




func jsonParsing()(){
    //check if strUrl not nill then enter this block
    if strUrl != nil{


        var request = URLRequest(url: URL(string: strUrl!)!)//get requet from urlRequest
        let session = URLSession.shared //creat session object

        request.httpMethod = "GET" // set http method

        //get data from url using session.datatask methos
        session.dataTask(with: request) {data, response, error in
            if error != nil{
                print(error!.localizedDescription)
                return
            }
            do{
                //get json result and store in dictionary
                let dicJsonResult = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
                let arrData = dicJsonResult["data"] as! NSArray // set friend list in array
                self.tblView.reloadData()
            }
            catch
            {
                print(error.localizedDescription)
            }
            }.resume()
    }else{
        print("No more friends")
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM