简体   繁体   English

变量名与函数名冲突导致“变量在其自身的初始值内使用”

[英]Variable name conflicts with function name leads to “Variable used within its own initial value”

Having this function有这个功能

private func date(from string: String) {
    // Do thing with string
}

when calling it with调用它时

let date = date(from: "11:30")

it produces the following error它产生以下错误

Variable used within its own initial value

obviously changing the code to显然将代码更改为

let anythingButDate = date(from: "11:30")

will make the error go away but I am trying to understand why there is a conflict between variable name and method name in the first place.将使错误消失,但我首先试图理解为什么变量名和方法名之间存在冲突。

UPDATE :更新

To be more precise - I understand that the compiler is having issues with giving the variable and the function the same name but I am curious why can't it distinguish that one is a variable name and the other is a function name.更准确地说 - 我知道编译器在给变量和函数同名时遇到问题,但我很好奇为什么它不能区分一个是变量名,另一个是函数名。

There is no big distinction between functions and variables because even a variable can hold a function or closure.函数和变量之间没有太大区别,因为即使是变量也可以包含函数或闭包。 What you have is a conflict of identifiers.您拥有的是标识符冲突。

You can use您可以使用

date = self.date(...)

to make the intent clear.以明确意图。

Your function is called date , even though it has a parameter it will conflict if you´re trying to call a variable the same name in this case date .你的函数被调用的date ,即使它有一个参数,如果you're试图调用一个变量在这种情况下,相同的名称将发生冲突date What happens is that the compiler tries to use the declared constant date to assign its own initial value.发生的情况是编译器尝试使用声明的常量date来分配自己的初始值。

When you use anythingButDate then it´s fine because your function is not called that and you don´t have any other function called anythingButDate .当您使用anythingButDate然后it's很好,因为你的函数不叫这一点,你没有必要叫任何其他功能anythingButDate

let date = date(from: "11:30") // will not work
let datex = date(from: "11:30") // will work
let anythingButDate = date(from: "11:30") // will work

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

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