Swift Error: Variable used within its own initial value

大憨熊 提交于 2019-12-18 10:58:13

问题


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 ?


回答1:


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.




回答2:


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

By adding if resolved above issue.




回答3:


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)
}



回答4:


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.



来源:https://stackoverflow.com/questions/24050599/swift-error-variable-used-within-its-own-initial-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!