简体   繁体   English

错误:变量在其自身的初始值内使用?

[英]Error: Variable used within its own initial value?

i'm trying to convert source code developed in Xcode 6.4 into Xcode 7. I'm getting some new errors.我正在尝试将在 Xcode 6.4 中开发的源代码转换为 Xcode 7。我遇到了一些新错误。 Below code which works fine in Xcode 6.4 is not working in Xcode 7下面在 Xcode 6.4 中运行良好的代码在 Xcode 7 中不起作用

 for (index: String, category: JSON) in json["payload"]["categoryList"] {
        let category:Category = Category(category : category)
      categoryList.append(category)
    }

Update your code like below,更新您的代码,如下所示,

for (index: String, cat: JSON) in json["payload"]["categoryList"] {
        let category:Category = Category(category : cat)
      categoryList.append(category)
    }

It's good habit not to confuse the compiler by reusing variable names as parameter names and local variables in the same scope.最好不要通过在同一范围内将变量名重用作参数名和局部变量来混淆编译器。

Better write:最好写:

for (index: String, category: JSON) in json["payload"]["categoryList"]  {
  let categoryListItem = Category(category : category)
  categoryList.append(categoryListItem)
}

or even甚至

for (index: String, category: JSON) in json["payload"]["categoryList"] {
  categoryList.append(Category(category : category))
}

The type annotation Category is not needed.不需要类型注释Category The compiler infers the type编译器推断类型

for (index: String, categoryJSON: JSON) in json["payload"]["categoryList"] {
    let category:Category = Category(category : categoryJSON)
    categoryList.append(category)
}

Actually i found answer for my question in swift 2.0 they changed syntax of for loop实际上我在 swift 2.0 中找到了我的问题的答案,他们改变了 for 循环的语法

for (key,categoryJSON):(String, JSON) in json {
        //Do something you want
        let category:Category = Category(category : categoryJSON)
        categoryList.append(category)

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM