ios Swift 错误:变量在其自己的初始值内使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24050599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 00:29:09  来源:igfitidea点击:

Swift Error: Variable used within its own initial value

iosswiftios8xcode6

提问by Francescu

When I'm initializing an instance of an entity I'm getting the error Variable used within its own initial value.

当我初始化一个实体的实例时,我收到了错误Variable used within its own initial value

Here is the code throwing the error:

这是抛出错误的代码:

class func buildWordDefinition (word:String, language:Language, root:TBXMLElement) -> WordDefinition
    {
        let word = WordDefinition(word: word, language: language)

The error points at the wordvariable.

错误指向word变量。

Here is the WordDefinition class:

这是 WordDefinition 类:

class WordDefinition {
    let word: String
    let language: Language

    init(word: String, language:Language)
    {
        self.word = word
        self.language = language
    }
}

What does this error mean ?

这个错误是什么意思 ?

回答by Cezar

You are declaring a constant named word, and trying to use the argument with the same name to initialize it. The compiler tries to use the just declared constant to assign its own initial value, instead of using the argument.

您正在声明一个名为 的常量word,并尝试使用具有相同名称的参数来初始化它。编译器尝试使用刚刚声明的常量来分配它自己的初始值,而不是使用参数。

回答by Shrawan

I have faced same error when missing out ifwhile unwrapping the text .

如果在展开文本时错过了,我也遇到了同样的错误。

enter image description here

在此处输入图片说明

By adding if resolved above issue.

通过添加如果解决了上述问题。

enter image description here

在此处输入图片说明

回答by Rod

You are redefining a constant wordwhich has the same name as a parameter within your function

您正在重新定义word与函数中的参数同名的常量

class func buildWordDefinition (word:String, language:Language, root:TBXMLElement) -> WordDefinition
{
    // same name as the parameter here
    let word = WordDefinition(word: word, language: language)
}

回答by gwcoffey

You have a function parameter called wordin scope and you're trying to create a constant with the same name. Name your constant something other than word.

您有一个word在作用域中调用的函数参数,并且您正在尝试创建一个具有相同名称的常量。将常量命名为word.