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
. What happens is that the compiler tries to use the declared constant date
to assign its own initial value.
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
.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.