[swift-evolution] Why doesn't Swift allow a variable and a function with the same name?

Austin Zheng austinzheng at gmail.com
Mon Jan 30 13:42:20 CST 2017


The reason Swift works like this is because you can assign a function value
(independently of calling it) to a variable. So there aren't two separate
namespaces separating function names and variable names.

To wit:

func randomArray(withCapacity capacity: Int) -> [Int] {
    // ....
}

// An array of Ints, the result of calling the function.
let myValue : [Int] = randomArray(withCapacity: 10)
// A function, of type Int -> Array<Int>.
let myFunc : ((Int) -> [Int]) = randomArray

Best,
Austin




On Mon, Jan 30, 2017 at 11:37 AM, Michael Gubik via swift-evolution <
swift-evolution at swift.org> wrote:

> Example that does not compile:
>
>             let randomArray = randomArray(withCapacity: 4096)
>
> Compiler error: “Variable used within its own initial value”
> The variable name unfortunately clashes with the function name.
>
> This problem forces the developer to think about an alternative name.
> IMHO that’s suboptimal since many times the most canonical naming would be
> one where these two go by the same name.
>
> It’s not a big problem in practice but I wonder if there are plans to
> change this?
>
>
> Thanks,
> Michael Gubik
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170130/1b3534b5/attachment.html>


More information about the swift-evolution mailing list