简体   繁体   中英

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. Below code which works fine in Xcode 6.4 is not working in 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. 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

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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