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:

//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:

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 🤨

More from Medium

Creating a Service Layer in Swift

Five Notes about iOS Application with MVVM Architecture

Tips

From ObjC → Swift → ObjC: Part 1

The UIPickerView Guide (Swift Tutorial)