3

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.

tonymontana
  • 5,728
  • 4
  • 34
  • 53

2 Answers2

5

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.

Sulthan
  • 128,090
  • 22
  • 218
  • 270
  • That's what I was looking for. Missed that. – tonymontana Oct 31 '17 at 20:03
  • Considering that it can infer stuff like this in optional binding in guards like `guard someOptional = someOptional else { ... }` this is pretty stupid that it can't infer that the right hand side is an application of a function named `date(from:)` that needs to be assigned to a constant called `date` especially since `date(from:)` is not defined anywhere in the current scope so it's not like there's a local scope function/closure variable called `date` that it's getting hung up on. `date` is a poor example since this should be a convenience constructor on an extension of Date, but still – Beltalowda Nov 17 '17 at 18:06
  • @thuggish-nuggets you are wrong. When referencing a method using its name, only its first part is used. That means there actually is a method called `date`. That optional binding is a very specific case because it intentionally shadows a variable. – Sulthan Nov 17 '17 at 21:58
  • Sure but the presence of parenthesis and an argument list indicates the function is to be applied, not treated as a variable. There is no reason the compiler should not be able to infer this case. – Beltalowda Nov 17 '17 at 22:01
1

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
Rashwan L
  • 38,237
  • 7
  • 103
  • 107