我对变量'tb'的声明感到困惑,我希望它到处都是.这个变量来自JSON.
如果我直接从JSON初始化
var tb = json as! Array<Dictionary<String, Any>>
Run Code Online (Sandbox Code Playgroud)
它正在工作,但它没有确定tableView函数的范围.
我仍然是一个快速的初学者,所以如果有人能解释我该怎么办?以及这个范围和变量init/type如何工作,我将非常感激.
这是代码:
class BiensViewController: UIViewController {
@IBOutlet weak var maTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
var user = ""
var tb:[Dictionary<String, Any>]
super.viewDidLoad()
//on récupère l'utilisateur courant.
let fm = FileManager.default
let urlRepDocuments = try! fm.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let url = urlRepDocuments.appendingPathComponent("user.plist")
print(url)
if let dico = NSMutableDictionary.init(contentsOfFile: url.path){
if dico["email"] != nil {
user = dico["email"] as! String
}
}
let parameters = ["email": user]
//
guard let httpUrl = URL(string: "https://mysite.000webhostapp.com/services")else{return}
var request = URLRequest(url: httpUrl)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else { return }
request.httpBody = httpBody
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let response = response {
print("******")
print(response)
}
let json:Any
if let data = data {
do {
json = try JSONSerialization.jsonObject(with: data, options: [])
//print(json)
tb = json as! Array<Dictionary<String, Any>>
print(tb)
} catch {
print(error)
}
}
}.resume()
func numberOfSections(in tableView: UITableView) -> Int
{
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return tb.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
//Récupéré une cellule réutilisable
let cellule:BiensTableViewCell = tableView.dequeueReusableCell(withIdentifier: "maCellulePersonnalise", for: indexPath)
as! BiensTableViewCell
//peuple la cellule
cellule.etqRef.text = tb[indexPath.row]["ref"] as? String
cellule.EtqAdresse.text = tb[indexPath.row]["adresse"] as? String
cellule.etqCP.text = tb[indexPath.row]["cp"] as? String
cellule.etqVille.text = tb[indexPath.row]["ville"] as? String
cellule.etqNomLoc.text = tb[indexPath.row]["nom"] as? String
cellule.etqLoyer.text = tb[indexPath.row]["loyer"] as? String
return cellule
}}}
Run Code Online (Sandbox Code Playgroud)
错误是:
在初始化之前由闭包捕获的变量'tb'
您只需在viewDidLoad()之外声明变量,就在绘制出口的位置下方.目前,您的变量仅限于viewDidLoad()的范围.但现在它将在完整的课程中访问.
class BiensViewController: UIViewController {
@IBOutlet weak var maTable: UITableView!
var tb = [Dictionary<String, AnyObject>]()
//or you can use:- var tb = [Dictionary<String, Any>]() according to your requirement
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
71 次 |
| 最近记录: |