Swift Error: Variable used within its own initial value

IosSwiftIos8Xcode6

Ios Problem Overview


When I'm initializing an instance of an entity I'm getting the error 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.

Here is the WordDefinition class:

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

What does this error mean ?

Ios Solutions


Solution 1 - Ios

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.

Solution 2 - Ios

> I have faced same error when missing out if while unwrapping the > text .

enter image description here

By adding if resolved above issue.

enter image description here

Solution 3 - Ios

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

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

Solution 4 - Ios

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFrancescuView Question on Stackoverflow
Solution 1 - IosCezarView Answer on Stackoverflow
Solution 2 - IosShrawanView Answer on Stackoverflow
Solution 3 - IosRodView Answer on Stackoverflow
Solution 4 - IosgwcoffeyView Answer on Stackoverflow