Intro to Generics in Swift 3

Let’s talk to Generic. He’s alive.

Generics Are Beautiful. We Love Generics.

Generics. Podcast.

Here we go.

INTRO

I’ve been listening to Joe Rogan’s Podcast recently hence this article will take place in the format of podcast for a different flavor. I hope you enjoy.

SWIFT TONIGHT’S SHOW

Hot from Hollywood, we have the one and only Generic.

Me: Welcome Generic to Swift Tonight’s Show. How you doin’ ?

G: I mean I’m generic.

WHAT ARE GENERICS

Me: Alright cool we have 20,000 live viewers here tonight. A lot of our viewers back at home want to know more about you Generic. Would you mind explaining what make you Generic, the Generic?”

G: “Cool cool. Well you see. The Swift library loves me. I love the Swift library. I know your Swift Tonight’s Show is pretty advance and can do some real time hyperlink. Is that true?”

Me: “We not 100% there yet, but our beta is 90% strong for all cases so far. Anytime we have great resources, we shall try and hyperlink.”

G: “Hey man, I respect you for the honesty man and that’s coming from a G. Alright so about me. What I do. What I do is I adapt. I am meant to adapt. I believe the reason for my existence is that I can be put in different scenarios and adapt. It’s like me or many functions.”

WHY USE GENERICS

G: Here check this out. My non-generic function brothers would do this. Say they want to create a function that print all the elements inside of an array of type Int.

//Declare
func printIntElements(_ array: [Int]) {
array.map { print($0) }
}
//Call
printIntElements([1, 2, 3, 4, 5])
//Console
1
2
3
4
5

You see where I’m going with this?

Me: Generic. You on another level man.

G: Thanks man. Check this out. My non-generic brothers out there would be like. Yo. I need another function to print out all the doubles. Then another for all the strings. Then another for whatever type. I mean that’s not cool. I’m sippin on some Bonaccino over here. All a sudden, they taking up my space. Space is expensive here in SF man. For real. They can’t do me like this.

func printDoubleElements(_ array: [Double]) {
array.map { print($0) }
}
func printStringElements(_ array: [String]) {
array.map { print($0) }
}

Me: So what you do?

G: This is where I kick in.

GENERIC FUNCTIONS

G: Being a Generic type, like I mentioned, I adapt. Give me fire or ice. I’ll still eat it up. I’m like Eminem. Slim Shady from the Marshal Mathers LP 2. I also like his Recovery album. One of the greatest album of all time.

Check this out.

func printWhateverTypeElements<Generic>(_ array: [Generic]) {
array.map { print($0) }
}

Me: Whow whow whow. What is that? That looks crazy. Hold up hold up. Tell us what’s going on here. Drop us something bruh. Drop some hints bruh.

G: Alright exclusively coming from Swift Tonight’s Show. Check this out. First, notice the word Generic I put between < and >. I pick to put Generic there. You can put whatever. That’s something to note. You can literally put ABC just make sure the parameter of type generic follows. Typically, you’d want to use the letter T. That’s standard. Like this.

func printWhateverTypeElementsFrom<T>(_ array: [T]) {
array.map { print($0) }
}

Me: So the <Generic> or <T> after the function name represents a generic function. A generic function can work with whatever type.

G: That’s right.

Me: What else do we need to know you Generic?

G: Difference between placeholder type and actual type.

PLACEHOLDER TYPE VS ACTUAL TYPE

G: Generic and T are called placeholder type names.

Int, String, and Double are actual type names.

Placeholder type names do not say what Generic or T must be unlike the actual type names. It’s flexible. However, it does say that the parameters that are declared as type T must be of the same type when called.

Here is a function that takes in two parameters of type T.

func swapTwoValues<T>(_ a: inout T, _ b: inout T) {
let tempA = a
a = b
b = tempA
}

If A and B are of different types. Boom.

var a = 10
var b = "20"
swapTwoValues(&a, &b) // 😡 Not cool because of inconsistent types

However, we can do Int Int, Double Double, String String, and etc. Just has to be type consistent across all Ts.”

var a = 10
var b = 20
swapTwoValues(&a, &b) // 👊 We cool because types are consistent

Me: “Ok I see. So Generic. You have just introduced generic functions. What they are. How they differ from non-generic functions. How to form generic functions. How to create generic functions. Those are some dope bars you dropped there Generic.”

G: “I’m feeling good today. Woke up on the right side of the bed.”

TYPE PARAMETERS

Me: “Let’s talk type parameters. The audience and I are interested in knowing about type parameters. Let’s talk type parameters.”

G: “That’s Major Key right there. I’m glad you mentioned it. Respect to you and the audience. Let’s talk type parameters.

The placeholder type T is a type parameter.

Type parameters are between a pair of matching angle brackets (ex. <T>).

func swapTwoValues<T>

Type parameters specify and name a placeholder type. We specify the parameter type when we call it. We name it when we declare it.

The type parameter is replaced with an actual type whenever the function is called.

Me: “Ok recap. Type parameters specify its type when being called. We name it when we declare it. We see that with <T>. T being the parameter type.”

G: “Yeah man. You got some mineral water. I need some mineral water.”

Me: Here you go.

*Hand over a bottle of water

G: This mineral water is lit.

NAMING TYPE PARAMETER

G: Look. Like I said. The standard default is T for a type placeholder. However, in most cases T doesn’t really say much. Hence we would want to have a more descriptive name like Key and Value in Dictionary<Key, Value> and Element in Array<Element>.This shows the relationship between the type parameter and the generic type or function it’s used in.

However, when there isn’t a meaningful relationship between the type parameter and the generic type, we use letters such like T, U, and V. Just head down the alphabet after T when we want to utilize more than one type in our generic functions.

Me: That’s a lot of information to digest. Here is an example that may help clear up the smokes.

//Declare
func anotherOne<T, U> (first: T, second: U) {}
func anotherOneAgain<T> (first: T, second: T) {}
//Call
anotherOne(first: 123, second: "456") // T - Int, U - String
anotherOneAgain(first: 123, second: 456) // T - Int

Once again, same type across all type parameters.

TYPE CONSTRAINTS

Me: Ok generic. I happened to bump into you the other day on the street. You showed me some type constraints. Let’s expand on that on this podcast because I think it is pretty important.

G: You see. Type constraints are important. It make your generic functions safer. When I specify the type parameter T, I can throw anything in there. Literally anything. It’s like although I have a big outdoor pond outside of my house, it doesn’t mean someone can throw in a shark to eat up all my fish.

Me: For real man. That’s deep.

G: Syntax.

You write type constraints by placing a single class or protocol constraint after a type parameter’s name

You write type constraints by placing a single class or protocol constraint after a type parameter’s name, separated by a colon, as part of the type parameter list.

func addFishToPond<T: CoolFish>(fish: T) {}

Now we can only pass in objects that are of type CoolFish with our addFishToPond.

Me: I mean that’s essential right there. Stop the vicious fish from eating up the good fish. Some times we got to limit what fish we put together man.

TIME UP

Me: “Well time’s up for today. It’s a pleasure Generic. Here take this Game of Throne’s dragon figure with you home. A token of thank-you-ness.”

G: “Hey my pleasure.”

WRAP UP

We have introduced generics. What they are. Why they are used. How to create generic functions. Type parameters. Naming type parameters. Type constraints.

Introduction, introduced.

2:54 AM. Time to dream about turning into a vicious fish.

LAST REMARKS

I hope you have enjoyed and learned something valuable from my article. If you have then let me know by hitting that ❤ button and follow me on Medium. Also, SHARE this article so that your circle can make some knowledge gains too.


SHOUT OUTS

Medium Recommends and Private Messages

Thank you all for your incredible support.

Medium Responses from Last Article

Durul Dalkanat, Alex McPherson, Kanna Jack, Talha Khalid, Marcos Detrovsky