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

Sentry mobile image

Mobile Vitals: A first step to Faster Apps

Slow startup times, UI hangs, and frozen frames frustrate users—but they’re also fixable. Mobile Vitals help you measure and understand these performance issues so you can optimize your app’s speed and responsiveness. Learn how to use them to reduce friction and improve user experience.

Read the guide →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more