如何将我的数组初始化为scoped

时间:2017-06-17 15:50:07

标签: swift

我对变量的声明感到有点困惑' tb'我希望它到处都是。此变量来自JSON。

如果我直接从JSON启动

var tb = json as! Array<Dictionary<String, Any>>

它正在运行,但它没有确定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

}}}

错误是:

变量&#39;&#39;在初始化之前由闭包捕获

1 个答案:

答案 0 :(得分:7)

您只需在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