Swift:不允许访问方法

时间:2015-07-19 16:24:39

标签: ios swift

我有一个问题。

我有以下方法:

   func CheckJSON(json: JSON) {
        for data in json["index"].arrayValue {

            let title = data["name"].stringValue
            let body = data["profil"].stringValue
            let obj = ["title": title, "body": body]
            objects.append(obj)
}


        tableView.reloadData()
    }

我想访问常数' body'在我的函数之外以及此文件之外。

我已经尝试过这样:

   func CheckJSON(json: JSON) -> String {
    for data in json["index"].arrayValue {

        let title = data["name"].stringValue
        let body = data["profil"].stringValue
        let obj = ["title": title, "body": body]
        objects.append(obj)



    }

    tableView.reloadData()
    return body
}

但是我得到了错误:

  

使用未解析的标识符' body'

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

变量的范围仅限于for循环本身。 当你在循环中声明一个变量时,你无法在循环外部访问它。变量的范围在循环中是有限的。如果你想要这个,你应该在循环之外声明变量,这样你就可以在函数中使用它作为返回。

所以代码看起来像这样:

// Right now you can acces the variable within the same file, and within a different file anywhere you want.    
var body: String! // Or a different type you want to give the variable
func CheckJSON(json: JSON) -> String {
  for data in json["index"].arrayValue {
    let title = data["name"].stringValue
    body = data["profil"].stringValue
    let obj = ["title": title, "body": body]
    objects.append(obj)
  }

  tableView.reloadData()
  return body
}

您可以使用以下代码访问文件外的变量:

// change instance to the name of your own class
var instance = exampleViewController()
// Call the variable.
instance.body
相关问题