tonymontana
tonymontana

Reputation: 5823

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.

Upvotes: 3

Views: 628

Answers (2)

Sulthan
Sulthan

Reputation: 130102

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.

Upvotes: 5

Rashwan L
Rashwan L

Reputation: 38833

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

Upvotes: 1

Related Questions