我对Swift相当新,我在理解如何做我想做的事情时遇到了一些问题。
我正在用json测试一些东西。 我想要做的是将我从json数据中获取的数据附加到数组中。 当我的数组包含我希望将它呈现给我的UICollectionView的数据时。 我假设我应该使用数组。
import UIKit import Foundation class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { @IBOutlet weak var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func getData() { let path = "http://myurl/test.json" let url = URL(string: path) let session = URLSession.shared let task = session.dataTask(with: url!) { (data: Data?, response: URLResponse?, error: Error?) in let json = JSON(data: data!) for result in json["dokumentstatus"]["dokutskott"]["utskott"].array! { let punkter = result["punkt"].string! print("punkt: \(punkt)") let rubrik = result["rubrik"].string print("rubrik: \(rubrik)") let forslag = result["forslag"].string print("förslag: \(forslag)") } } task.resume() } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return //someArray.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CustomCollectionViewCell cell.customLabel.text = //Put the data form rubrik variable cell.customTW.text = //Put the data from foreleg variable return cell } }函数getData()获取正确的json数据我只需要帮助理解如何将这些数据放入数组。 (另外,我知道我可能不应该在ViewController中获取数据,但这只是一个测试。)
import Foundation class Information: NSObject { var punkter: String? var rubrik: String? var forslag: String? }我想也许我应该使用一个看起来像这样的数组: var someArray = [Information]()但我不知道如何使用我的getData()或者我应该使用三个不同的数组,一个对于我的每个json变量。
I am fairly new to Swift and I am having a few issues with getting understanding how to do what I want to do.
I am currently testing some stuff with json. What I am trying to do is to append the data I get from my json data into an array. And when my array contains the data I wish to present it to my UICollectionView. I am assuming that I should be using an array.
import UIKit import Foundation class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { @IBOutlet weak var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func getData() { let path = "http://myurl/test.json" let url = URL(string: path) let session = URLSession.shared let task = session.dataTask(with: url!) { (data: Data?, response: URLResponse?, error: Error?) in let json = JSON(data: data!) for result in json["dokumentstatus"]["dokutskott"]["utskott"].array! { let punkter = result["punkt"].string! print("punkt: \(punkt)") let rubrik = result["rubrik"].string print("rubrik: \(rubrik)") let forslag = result["forslag"].string print("förslag: \(forslag)") } } task.resume() } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return //someArray.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CustomCollectionViewCell cell.customLabel.text = //Put the data form rubrik variable cell.customTW.text = //Put the data from foreleg variable return cell } }the function getData() gets the correct json data I just need help understanding how to put this data to an array. (Also, I know I probably shouldn't be getting the data in the ViewController, but this is only a test.)
import Foundation class Information: NSObject { var punkter: String? var rubrik: String? var forslag: String? }I'm thinking that maybe I should be using an array that looks something like this:var someArray = [Information]() But I do not know how to then use my getData() Or maybe I should be using three different arrays, one for each of my json variables.
最满意答案
既然你还在使用自定义类(做得好! 三个不同的数组很可怕),那么声明一个像你建议的数据源数组是正确的
var someArray = [Information]()结构很可能就足够了,我建议使用非可选字符串
struct Information { var punkter : String var rubrik : String var forslag : String }如果属性不会改变,你甚至可以使用let来制作属性常量。
要填充数组,请使用nil coalescing运算符检查nil ,使用memberwise初始化程序创建Information实例,并将实例附加到数据源数组。 然后在主线程上重新加载集合视图。
... for result in json["dokumentstatus"]["dokutskott"]["utskott"].array! { let punkter = result["punkt"].string ?? "" let rubrik = result["rubrik"].string ?? "" let forslag = result["forslag"].string ?? "" let information = Information(punkter:punkter, rubrik:rubrik, forslag:forslag) self.someArray.append(information) } DispatchQueue.main.async { self.collectionView.reloadData() } ...编辑:
要在cellForItemAtIndexPath显示数据, cellForItemAtIndexPath使用
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CustomCollectionViewCell let information = someArray[indexPath.row] cell.customLabel.text = information.rubrik cell.customTW.text = information.foreleg return cell }Since you're still using a custom class (well done!, three different arrays are horrible) it's correct to declare a data source array like you suggested
var someArray = [Information]()Most likely a struct is sufficient, I recommend to use non-optional strings
struct Information { var punkter : String var rubrik : String var forslag : String }If the properties won't change you could even use let to make the properties constants.
To populate the array use the nil coalescing operator to check for nil,create the Information instance with the memberwise initializer and append the instance to the datasource array. Then reload the collection view on the main thread.
... for result in json["dokumentstatus"]["dokutskott"]["utskott"].array! { let punkter = result["punkt"].string ?? "" let rubrik = result["rubrik"].string ?? "" let forslag = result["forslag"].string ?? "" let information = Information(punkter:punkter, rubrik:rubrik, forslag:forslag) self.someArray.append(information) } DispatchQueue.main.async { self.collectionView.reloadData() } ...Edit:
To display the data in cellForItemAtIndexPath use
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CustomCollectionViewCell let information = someArray[indexPath.row] cell.customLabel.text = information.rubrik cell.customTW.text = information.foreleg return cell }如何使用Swift将json数据添加到数组或类似数据(How to add json data to array or similar using Swift)我对Swift相当新,我在理解如何做我想做的事情时遇到了一些问题。
我正在用json测试一些东西。 我想要做的是将我从json数据中获取的数据附加到数组中。 当我的数组包含我希望将它呈现给我的UICollectionView的数据时。 我假设我应该使用数组。
import UIKit import Foundation class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { @IBOutlet weak var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func getData() { let path = "http://myurl/test.json" let url = URL(string: path) let session = URLSession.shared let task = session.dataTask(with: url!) { (data: Data?, response: URLResponse?, error: Error?) in let json = JSON(data: data!) for result in json["dokumentstatus"]["dokutskott"]["utskott"].array! { let punkter = result["punkt"].string! print("punkt: \(punkt)") let rubrik = result["rubrik"].string print("rubrik: \(rubrik)") let forslag = result["forslag"].string print("förslag: \(forslag)") } } task.resume() } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return //someArray.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CustomCollectionViewCell cell.customLabel.text = //Put the data form rubrik variable cell.customTW.text = //Put the data from foreleg variable return cell } }函数getData()获取正确的json数据我只需要帮助理解如何将这些数据放入数组。 (另外,我知道我可能不应该在ViewController中获取数据,但这只是一个测试。)
import Foundation class Information: NSObject { var punkter: String? var rubrik: String? var forslag: String? }我想也许我应该使用一个看起来像这样的数组: var someArray = [Information]()但我不知道如何使用我的getData()或者我应该使用三个不同的数组,一个对于我的每个json变量。
I am fairly new to Swift and I am having a few issues with getting understanding how to do what I want to do.
I am currently testing some stuff with json. What I am trying to do is to append the data I get from my json data into an array. And when my array contains the data I wish to present it to my UICollectionView. I am assuming that I should be using an array.
import UIKit import Foundation class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { @IBOutlet weak var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func getData() { let path = "http://myurl/test.json" let url = URL(string: path) let session = URLSession.shared let task = session.dataTask(with: url!) { (data: Data?, response: URLResponse?, error: Error?) in let json = JSON(data: data!) for result in json["dokumentstatus"]["dokutskott"]["utskott"].array! { let punkter = result["punkt"].string! print("punkt: \(punkt)") let rubrik = result["rubrik"].string print("rubrik: \(rubrik)") let forslag = result["forslag"].string print("förslag: \(forslag)") } } task.resume() } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return //someArray.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CustomCollectionViewCell cell.customLabel.text = //Put the data form rubrik variable cell.customTW.text = //Put the data from foreleg variable return cell } }the function getData() gets the correct json data I just need help understanding how to put this data to an array. (Also, I know I probably shouldn't be getting the data in the ViewController, but this is only a test.)
import Foundation class Information: NSObject { var punkter: String? var rubrik: String? var forslag: String? }I'm thinking that maybe I should be using an array that looks something like this:var someArray = [Information]() But I do not know how to then use my getData() Or maybe I should be using three different arrays, one for each of my json variables.
最满意答案
既然你还在使用自定义类(做得好! 三个不同的数组很可怕),那么声明一个像你建议的数据源数组是正确的
var someArray = [Information]()结构很可能就足够了,我建议使用非可选字符串
struct Information { var punkter : String var rubrik : String var forslag : String }如果属性不会改变,你甚至可以使用let来制作属性常量。
要填充数组,请使用nil coalescing运算符检查nil ,使用memberwise初始化程序创建Information实例,并将实例附加到数据源数组。 然后在主线程上重新加载集合视图。
... for result in json["dokumentstatus"]["dokutskott"]["utskott"].array! { let punkter = result["punkt"].string ?? "" let rubrik = result["rubrik"].string ?? "" let forslag = result["forslag"].string ?? "" let information = Information(punkter:punkter, rubrik:rubrik, forslag:forslag) self.someArray.append(information) } DispatchQueue.main.async { self.collectionView.reloadData() } ...编辑:
要在cellForItemAtIndexPath显示数据, cellForItemAtIndexPath使用
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CustomCollectionViewCell let information = someArray[indexPath.row] cell.customLabel.text = information.rubrik cell.customTW.text = information.foreleg return cell }Since you're still using a custom class (well done!, three different arrays are horrible) it's correct to declare a data source array like you suggested
var someArray = [Information]()Most likely a struct is sufficient, I recommend to use non-optional strings
struct Information { var punkter : String var rubrik : String var forslag : String }If the properties won't change you could even use let to make the properties constants.
To populate the array use the nil coalescing operator to check for nil,create the Information instance with the memberwise initializer and append the instance to the datasource array. Then reload the collection view on the main thread.
... for result in json["dokumentstatus"]["dokutskott"]["utskott"].array! { let punkter = result["punkt"].string ?? "" let rubrik = result["rubrik"].string ?? "" let forslag = result["forslag"].string ?? "" let information = Information(punkter:punkter, rubrik:rubrik, forslag:forslag) self.someArray.append(information) } DispatchQueue.main.async { self.collectionView.reloadData() } ...Edit:
To display the data in cellForItemAtIndexPath use
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CustomCollectionViewCell let information = someArray[indexPath.row] cell.customLabel.text = information.rubrik cell.customTW.text = information.foreleg return cell }
发布评论