How to overload functions in Swift

Issue #211

Function

Functions in Swift are distinguishable by

  • parameter label
  • parameter type
  • return type

so that these are all valid, and works for subscript as well

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
struct A {

// return type
func get() -> String { return "" }
func get() -> Int { return 1 }

// mix of parameter type and return type
func get(param: String) -> String { return "" }
func get(param: String) -> Int { return 1 }
func get(param: Int) -> Int { return 1 }
func get(param: Int) -> String { return "" }

subscript(param: String) -> String { return "" }
subscript(param: String) -> Int { return 1 }
subscript(param: Int) -> Int { return 1 }
subscript(param: Int) -> String { return "" }

// parameter label
func set(int: Int) {}
func set(string: String) {}

// concrete type from generic
func get(param: Array<String>) -> String { return "" }
func get(param: Array<Int>) -> Int { return 1 }

subscript(param: Array<String>) -> String { return "" }
subscript(param: Array<Int>) -> Int { return 1 }
}

When you specialize a generic type, like Array<Int>, you’re actually using a concrete type

Unfortunately, this does not work for NSObject subclass

Method ‘get()’ with Objective-C selector ‘get’ conflicts with previous declaration with the same Objective-C selector

1
2
3
4
5
class B: NSObject {

func get() -> String { return "" }
func get() -> Int { return 1 }
}

Generic function

We can overload generic functions as well

1
2
3
4
5
6
7
8
9
10
11
func f<T>(t: T) {
print("T")
}

func f(string: String) {
print("String")
}

func f(int: Int) {
print("Int")
}

Comments