DEV Community

Khoa Pham
Khoa Pham

Posted on

How to overload functions in Swift

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

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

class B: NSObject {

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

Generic function

We can overload generic functions as well

func f<T>(t: T) {
  print("T")
}

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

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

Original post https://github.com/onmyway133/blog/issues/211

Top comments (0)