简体   繁体   中英

Swift Variable used within its own initial value

I'm trying to initialize an object and I get this error: Variable used within its own initial value

Here is my code:

在此输入图像描述

Why can't I do it like this?

The others answers are correct. I would like to add a few suggestions here because I see many very ugly things in you code :[

1. Type names should be UpperCamelCase

So name your class Entity instead of entity

2. Extending NSObject...

Why does Entity extend NSObject ? Do you have a valid reason to do it?

3. Visibility

I see lots of public in you code. Why? Are you creating a library? Because probably there's no need to make public all that stuff.

4. Struct instead of Class

If Entity is simply a container for a bunch of data it should be a struct , not a class . You'll get better performance.

5. The "created" property declared as String? Seriously?

Too often I see code where the String type is used in place of many others types (such as Int , NSDate , Bool , ...). Why? This makes extremely difficult to deal with that value every time you need to perform some action/check strictly related the real type (like adding numbers, comparing dates, etc...)

6. Everything initialised to "", why?

What does it mean when created is an empty string? If you are using the empty String to indicate the absence of a value you should use nil instead (making of course the property an optional type).

Hope this helps :)

You can't give a variable the same name as a type: the compiler's getting confused and it thinks your reference to entry the type is referring to entry the new variable, hence the warning.

The best solution is to use CamelCase names for types and llamaCase names for variables, as recommended by Apple in "The Swift Programming Language". For example:

public var entry = Entry()

and

public class Entry: NSObject {

(Note also that you needn't explicitly state the type of the entry variable, as it's easily deduced from its value.)

You just have a collision of the name of the entry variable reference and the entry class. Just rename the entry class: make it "Entry" for instance.

Change the name of the instance because you can't use the same name as the class. In addition you should change the name of the class to uppercase where it becomes easier to differ class name and instance

var levelEntry = Entry()

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