Swift: functions and variables cannot have the same name

Originator:mail
Number:rdar://17247972 Date Originated:2014-06-10
Status:Open Resolved:
Product:Swift Product Version:
Classification:Enhancement Reproducible:
 
Summary:
Take this code:

func hello() -> Int {
  return 123
}

let hello = hello()

Declaring the variable "hello" gives an error, "Variable used within its own initial value". Swift does not recognize that hello, the variable, is different from hello(), the function.

Steps to Reproduce:
Create a function and a variable with the same name. Swift gets upset.

This also happens if the function is a member of a class and the variable is a local variable inside another function.


Expected Results:
I can have a function and a variable with the same name.


Actual Results:
Swift gives the error "Variable used within its own initial value" 

Version:
Xcode 6 beta 1

Comments

Welcome to a functional programming language! You'll find that things are a little different than you're used to. Functions are just regular values in functional programming languages. You might be used to languages where a function can never be used in a place where a value is expected, such as assignment to a variable. In Swift, functions can be assigned to variables, passed in to other functions as arguments, and functions can even return other functions. This means you can do something like:

let helloAgain = hello
let result = helloAgain()

// result == 123

It might be clearer why the compiler is confused if you consider this equivalent example:

let hello : () -> Int = {
  return 123
}

let hello : Int = hello()

hello is just a value. First you told the compiler its type is () -> Int, then you told the compiler its type is Int. In other words, you can't have hello mean two different things and that's not likely to change.

Your other issue sounds like a matter of scoping. The following code returns 133, as expected

class Example {
  func hello() -> Int {
    return 123
  }

func other() -> Int {
    let hello = self.hello()
    return hello + 10
  }
}

let result = Example().other()

Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!