Generics in iOS swift

let intArray = [1,2,3,4,5] // type intlet stringArray = [“abhi”, “iOS”] // type string
func printIntArray(arr:[Int]) {arr.map { print($0) } // loop through the array and print all values}
func printStringArray(arr:[String]) {
arr.map { print($0) } // loop through the array and print all values}printIntArray(arr: intArray) // prints all values in intArrayprintStringArray(arr: stringArray) //prints values in stringArray
func printAnyArray<T>(arr:[T]) {arr.map { print($0) }}printAnyArray(arr: intArray)printStringArray(arr: stringArray)

Generic function with multiple parameters:

The syntax is the same as before. Just add one more placeholder type along with the placeholder type T between the < and > i f you want to pass one more parameter of different kind to the generic function. Check the example below. you will understand better.

//Declare
func anotherMethod<T, U> (first: T, second: U) { print("first one called")}
func anotherMethod<T> (first: T, second: T) { print("second one called")}//Call
anotherMethod(first: 123, second: "456") // T - Int, U - String
anotherMethod(first: 123, second: 456) // T - Int

Generic function with type constraints:

Consider the following example:

func middleVal<T>(array: [T]) -> T? {
guard !array.isEmpty else { return nil }
return array.sorted()[(array.count - 1) / 2]
}
func middleVal<T: Comparable>(array: [T]) -> T? {
guard !array.isEmpty else { return nil }
return array.sorted()[(array.count - 1) / 2]
}

If you enjoyed reading this post, please share and recommend it so others can find it 💚💚💚💚💚💚 !!!!

--

--

iOS and tvOS developer, dreamer, photographer 🤨

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Abhimuralidharan

Abhimuralidharan

iOS and tvOS developer, dreamer, photographer 🤨