The type of the function is determined by the type of its arguments and the type of the return value, and the compiler can uniquely use named functions by type - from your example:
subscript(key: Int) -> Int { return 1 }
... has type (Int) -> Int
subscript(key: Int) -> String { return "hi" }
... has type (Int) -> String
- therefore, although they are named the same way, the compiler can determine which one is caused by the way the return value is assigned (or since it is a subscript
value, to which value this index is assigned)
continues:
func getSomething() -> Int { return 2 }
... has type () -> Int
func getSomething() -> String { return "hey" }
... has type () -> String
Note: where you may run into a problem if you do not provide the compiler with enough information to determine which function you are calling, for example. if you just called getSomething()
without doing anything with its return value, it will complain about ambiguous use of 'getSomething'
EDIT - oh, now I see in your code example that you really provide an example where this is so :) by assigning the return value to a constant for which you did not specify the type ( let x = getSomething()
) there is not enough information for the compiler to figure out what function you are calling
EDIT EDIT - note that when I start with “the compiler can resolve ambiguous named functions by type”, the names of the functions are defined: (1) the identifier of the function, as well as (2) the identifiers of the names of the external parameters of the function - for example although the following two functions have the same type and function identifier, they are different functions and have different function names, because they differ in identifiers used for their external parameter names:
func getSomething(thing: String, howMany: Int) -> String
... is of type (String, Int) -> String
and is called getSomething(_:howMany:)
func getSomething(thing: String, howManyTimes: Int) -> String
... is of type (String, Int) -> String
and is called getSomething(_:howManyTimes:)