简体   繁体   English

Swift Error:变量在其自己的初始值内使用

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

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 word variable. 错误指向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 ? 这个错误是什么意思 ?

You are declaring a constant named word , and trying to use the argument with the same name to initialize it. 您正在声明一个常量命word ,并尝试使用具有相同名称的参数来初始化它。 The compiler tries to use the just declared constant to assign its own initial value, instead of using the argument. 编译器尝试使用刚刚声明的常量来分配自己的初始值,而不是使用参数。

I have faced same error when missing out if while unwrapping the text . 如果在解开文本时错过了,我遇到了同样的错误。

在此输入图像描述

By adding if resolved above issue. 通过添加if解决上述问题。

在此输入图像描述

You are redefining a constant word which 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)
}

You have a function parameter called word in scope and you're trying to create a constant with the same name. 您在作用域中有一个名为word的函数参数,并且您正在尝试创建具有相同名称的常量。 Name your constant something other than word . 将你的常量命名为除了word以外

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

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