2015-07-19 98 views
-2

我有一个问题。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() 
    } 

我想访问常量“身体”我的功能之外,也超出这个文件。

我已经尝试过这样的:

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 
} 

,但我得到的错误:

Use of unresolved identifier 'body'

任何想法?

回答

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 
+0

谢谢,但我得到了以下行错误:对象.append(obj) –

+0

错误:无法用类型为'([String:String!])'的参数列表调用'append'' –

+0

将其更改为var body =“” –