Treehouse Intermediate Course - Part 3 (Generics 1)

Yes the momentum continues! Today the aim is to cover half of the Generics bits. I know a bit about these but can't think much else other than downcasting/upcasting. There'll be more for sure! Also, I am going to ensure to do the extra reading parts, where relevant, as well as any coding practice. 

Start Time - 15:04

Writing Repetitive Code

So generics presumably means using the 'any' type and avoid using repetitive code. So I was right in that sense! Also, this links to the F1 quiz I've done before, which is in dire need of other options. Need to have sections for drivers, teams or difficulty level...I had to give up on that project back in January.

Back to the course! Loops for example are an elegant construct - much better than typing out verbose code!

func swapInts(_ a: Int, b: Int) {
    var tempA = a
    a = b
    b = tempA
    
    
    
}


swapInts(4, b: 7)

The above does not work as a and b are lets - automatically so as they are parameters. 

func swapInts(_ a: inout Int, _ b: inout Int) {
    let tempA = a
    a = b
    b = tempA
    
    
    
}

var c = 5
var d = 9

swapInts(&c, &d)

Right so several things here. First of all the inout keyword is used so that the a and b values are now variables - they can be mutated/changed! Also the and symbol (&) is used for calling them in the call of swapping c and d. 

OK Pasan starts showing swapping strings. 

I'm going to beat Pasan to it here. So I'm going to tweak the function rather than create a brand new one. Ok tried that, not quite! Pasan is creating a new function, but I know that this will be simpler and use something to do with Any....surely!

So the key here is about avoiding repetitive code and avoiding potential errors!

Yes, it is Any!

This is what I tried, which Pasan is just explaining why this won't work - type safety!

Writing Generic Functions

Ah yes! The <T>! Let's try that before Pasan shows....

Paused at 15:23; restart at 16:02


Yes! Really rewarding to get the rest of the syntax right!

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

var c = 5
var d = 9

swapValues(&c, &d)

So that makes total sense - the type is the letter 'T'. You can use another keyword or letter technically, but T is the considered, generic way of doing it. 

It is a generic function as it uses a placeholder type name in place of an actual type name. 

So this is a cool idea if you have different types...just thinking about classes for a moment. Yes if you have different classes e.g. the question types in my F1 quiz app, then that could work. I will have another go at that tomorrow, after the generics course is done!

Back to the course! You have to put the same type in for the above. So an error would come up if you tried swapping an int with a string!

OK challenge time! Then I'm going to do some extra reading...


So with this, let's just break it down. I need the function, the <T>, the two arguments and then all of the return bit. That should be ok....

func duplicate<T>(item: T, numberOfTimes: Int) -> [T] {
    let array = Array(repeating: item, count: numberOfTimes)
    
    return array
}

Tricky! I looked up ways to add to an array as the for loop wouldn't work. So the Array with the repeating method is best. I'll submit that and see...

Woohoo! Sweet! 

Now one more video, then some extra reading! I'll save the next challenge until tomorrow/next time!

Multiple Parameters

So the convention to have more than one type would be after T - so U, V etc. etc.

OK I agree with the comments - a strange example to do when we have methods for transforming between types already!

No point going over that much more. 

Extra Reading

https://docs.swift.org/swift-book/LanguageGuide/Generics.html

Right so the example here is EXACTLY the same one Pasan used, convenient!

The next bit of info following this is about type parameters. I know I've looked at type properties before...Anyway, type parameters are the <T> part - specified right after the base name and before the argument labels. They should always be in UpperCamelCase and I already mentioned the T, U, V convention. 

https://www.raywenderlich.com/3535703-swift-generics-tutorial-getting-started

One of the points he makes in the tutorial is that various types - arrays, dictionaries, optionals and results(?) are generic types. 

Arrays - ah yes, I see. You can create an array of Ints, Strings, Doubles etc. As long as they're of the same type then it's all good. 

Also append is a generic method. It will conform to the same type...and it will work for strings, ints - as before. 

OK, Results is a new type in Swift 5, exciting! With Results you can return a value or error without using the 'try' syntax. I'm not going to look anymore at Results yet!

OK, there is more about generics - extensions, subscripts...but that's a bit ahead of me and I am done for now!

Finish Time - 16:45 (1 hour and 2 minutes total)

So there we go! First part of generics. The key thing here is a) I'm not cramming too much in - second part of generics next time - and b) I am using extra reading to help go over anything and find out a little more. Ray's points about generics being used in other types is genuinely interesting! Good stuff; I am building my knowledge and getting there slowly, one concept at a time!

Comments

Popular posts from this blog

*Xcode Project Entry 2* F1 Quiz - part 1

Angela Yu Course Part 10 (up to lesson 112)

Angela Yu Xcode 12 Course - Part 7 (lectures 74 to 79)