DEV Community

Khoa Pham
Khoa Pham

Posted on

2 1

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

đź‘‹ While you are here

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

Top comments (0)

đź‘‹ Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay