Type Casting in Swift

Bob Lee
A free video tutorial from Bob Lee
iOS Instructor | Bob the Developer
4.7 instructor rating • 1 course • 1,579 students

Learn more from the full course

Learn Swift 4 with Bob: The Intermediate to Advanced Swift

Functional Programming, Protocol Oriented, Value Oriented, Generic Protocols, Object Oriented, Swift 4

17:38:08 of on-demand video • Updated September 2017

  • Learn the difference between classes and structs and which one to use
  • Learn how to create generic enums, structs, classes, protocols
  • Get a taste of functional programming with trailing, auto, and escaping closures
  • Understand how objects are created and removed through Automatic Reference Counting
  • Understand potential retain cycle in closures, delegate, and class variables
  • Understand Swift is a protocol oriented programming language
  • Apply protocols such as Equatable, Comparable, Sequence, and IteratorProtocol
  • Execute Swift files using Terminal/Command Line
  • Functional Programming
English [Auto] Come to Lesson 5 of the sweet fundamentals it since lesson one you've learned a number of question marks and those bangs and swift these are language features that distinguish Swift from the rest. And you've got to know when where how and most importantly get to know why you use it in this lesson you will learn how to convert types of an object that are created with classes instruct the storyboard in Iowa. Veltman you have to use typecasting before. So let's find out what goes on there Neith who the rag is welcome to typecasting in this lesson we'll take a look at how do you distinguish between as as questionmark and as XO on the exclamation mark. And also why does X code keep telling you what to do. I'm sick of it and most Iowas big intros Albers faced his problem right. Why does ex-coach keep telling what to do. And this lesson we can to prevent that from happening. OK. So first of all you have seen something like this in the past. Typecasting you like it or you Wiking of label you've created that label object and sometimes you feel like what is your white view right there but why is this happening. OK well let's try replicate this feature by using a custom class word. What are you doing right now is it literally converting you UI label to your idea. But I'm Mike explained to you by creating our own class. So first of all McRea a classical human simple classical and contains a method or introduce and then you want to create that. You also want to create a subclass that inherits the Korean Human class and I'm a Cola's Korean. OK. And also contains this beautiful method they call sing Gangnam Style. OK. And they print OPA Gangnam Style. All right that's a Korean way of saying ok cool. So if you make an object we're called Bob. Bob is Korean object not only contains an introduced method that in herds from the human object a human class but also you have the single homestyle claw method that comes from a Korean. OK. All good again. But now sometimes Locy Hey can I convert Bob. Right now the type of Bob is green. Can I convert to type of Bob to human. Is it possible. Yes you can. So let me ask let me tell you how you do it. We call this type casting. You are able to convert type. For example you can simply say lead Bob knew Bob Bob as human so he could look on it now. Now Bob becomes human and of course you'd read removed it as human part. It's literally just a screen. But of course if you now as human Now it becomes a human type. But if you know correctly human type only contains one method or eight It doesn't contain a single cell. Well let's take a look at it. New Bob and introduced it definitely contains at hello I'm a human on the bottom here. But it does not contain what we call that single cell. It doesn't contain that met widely. So you've converted Bob from Korean to human. OK. We call this process of casting. Here's why we call this upcast and here's why. Well let's go back to understand what casting mean it's important it's it's better to take a look at this example. So this is an UI issue. You like your framework Don't get overwhelmed going to take a look at this you view and you are label here you label is a subclass of white view. So anything that has a UI view also UI label has it. But here when you create this object you are simply creating this UI label here. But what you're doing is you are converting to UI view. OK you've said you're able to do that because it's it is a UI label is a subclass of view. OK. That's possible. As we've stated before just like here with a career in human relationship. But when you're doing it what you're doing is you're up to task and you're going up you're going up to the letter going more generic. And yeah that's called up casting you're up converting. And the opposite will be downcasting right. Coming from you I view you a label I'm going to talk about it in a second. OK. So help us understand up casting is as nothing more than converting from from specific types to DeGeneres type that while your which you inherit from. OK. That's called up casting. And when you do upcast and you use as it's always going to work why zester. Because if you think about it upcast thing is getting rid of properties and values and a method. So if you if you if you upcast from Korean to human you're getting rid this single cell and any property that are associated treeing a class you if you get rid of something. Well you know you can always it's always going to work right. So if you get rid of it then it's going to work. Right. So now about as human introduced it works. I hope that makes sense to you if you write. It's always going to work. Becoming More generally I hope that makes sense. Hopefully making sense. Ziel again if you use as means you're upcast thing is always going to work ok. Always going to work. Let's create a dummy called Japaneses Well human you know danger. But it doesn't mean much. Just don't use it for later example. OK. So I want to give you a upcast an example with the swift language I'm up casting with with normal slash common types. So for example you can have a Varn name. Let's call this Bob. Oregon use your own name. And also we have numbered tolt 20 right now. So if you take a look at it right now the number name is string and also a number is also in. But here you can also convert to a generic type which is all any. OK you guys probably send it before you can convert to any. But here's a magic but why do we upcast in the first place. Well the benefit would be you are able to combine similarly non-related object into one single array. This is what I mean by that you are able to do something like this. Any array equals name come on number. If you order to use without upcast then you're not allowed to do that you're not allowed to store by a string and end in a single ray. You're not allowed to do that. So you have to convert upcast to the very top tier. Any is a little something that just exists by default in the swift firmament language. OK you're able to combine into something like that. So that's that's what upcast thing is. Both are making sense to you. OK. So here's a problem. Sometimes you want to downcast it. So what I mean by that is OK this array contains no name but now you want to work with it individual level. So what do you have to do is you have to downcast and you want to convert from any to normal type which is a string. So and downcasting as I said is the opposite of upcast and you're going from you want to you want to label that downcasting. OK. But here's a problem you want you can technically you can be image view could be you might view you like control could be you view however. You my view can also be you table view or image view or label view I set you right from the bottom to top. The always converges into you view but from my view it diverges into many sections. So what does that mean. Well you can say hey you don't exactly know whether name right is a string or not. You don't exactly know where the number is because I call it name number. You can kind of tell them this is great but sometimes you cannot tell what they are does and what value was typed. It contains bytes. DNA. So sometimes you might fail to recognize a string. Is it string or is it. And so downcasting on the other hand may fail. OK. Upcast thing may work always or always always were always works. But downcasting on the other hand may fail. OK. So there are two ways to downcasting one is a safe way and one is Z the force way. OK so this part we've covered as part as many is the use for up casting. But when it comes downcasting we're going to use this to get. So let's try to downcast. Let's started down Kaz number and name so downcast. We only have to do is just going to copy the titles and subtitles downcast. Well let's talk about the forced downcasting So let's get the new value from any array. Let's get them let's get the number so be one right and the only thing you have to do right now if you take a look at it is any right. But you want to downcast it from any two specific type which is you have to use it like that. You're not allowed to notice this as is only used for up casting right now. Downcasting you have to use either exclamation mark or question mark. So what you get is you get this normal type or a normal type return normal time. You get this normal time. But here's a problem right. Sometimes you are not able to guess what the type the original type will might be like. So what about another value and the array. And if you do something like this bright you get to have a lot of air. I have a problem. Why decile because binds DNA as you know number bytes DNA is string. Right. So it is it. And if you try to force a typecast to a string it's not going to work that way. Hey you cannot convert from Swift into six string so force or mapping. Not going to work. So as you know you don't want to force anything when it comes to programming. So this is not the best practice. Try not to use force. Downcasting because it might fail. So here comes a safer way which we which we call it as implicit downcasting the safer way using the optional way. So what I would do is something like this new new value equals any array right now that zero is name and binds DNA. It is not. It is. It is screwing but if you try to do as then it will simply get in return nil. So what does that mean. If you take a look a new value is optional so. So in swift as an as you see this questionmark you are expected to see an optional value. OK. That's a rule. OK that's it. And of course when you get the right type. So right now any array right now is number right. If you started downcasting where the question mark it yet it's going to work. But the only problem is you're going to get an optional type which is in questionmark So you have to unwrap it either using it flat or just like something like that if you want it to. But of course in real practice you're going to use the safer way of using it. So far we talked about it. Why do we even downcast in upcast you might have that question right now. Well don't worry you get to walk on a walk through why this is might be useful but not the best practice. But we can also learn a lot from this lesson. Well let's talk about this what Alan does and what you with down count up casting allows you to do as you seen here it allows you to group objects that are simply different and they don't look then they don't share that type together into a single array or a dictionary or sets. So an example sort of created a couple of people names Japanese Korean That's Park is my mom's last name is my last name. All right. So there are little There are there are different types right. There are Japanese type Korean type Japanese cybering type. However they all share the fundamental root was a fundamental root. If you go back here they actually all come from human. OK. And here's a magic happening. You are able to do something like this like the humans shown as human like as a human Kenya's human park as human. OK. And also specify that this is a human type. But in fact swaped was smart enough that as long as you share the same parents you are able to do something like this. She only can you part because she old comes from human. Li Li comes from Makenzie they automatically upcast that 40 is over. Now take a look at OBS and click on it. Let's show Japanese. But at the end it all all converges to human type. So if you don't believe. Let's take a look at its human dot once get zero and it should contain that ingenues use function. It doesn't really have that it doesn't have what it called. Do ninja function. It doesn't have it. Right the only function it has is a human. It's associated with human which is introduced. OK. So why is this useful. Well we're going to take a look at this. You can do something like that. You can use foreign live. You can say for human in humans. OK. And you can see if led. Korean. Let's create a constant. Korean and human as Korean if it's korean then you can say Korean does sing sing. Where is that single on himself right there. And if the human right now is Japanese Japanese equals human as safely unmap Japanese you can say Japanese do Ninja. So what's happening is you were able to group them together. Now you're able to run their own distinct function method associated with human and Japanese just like the magical you're able to group them together and then will allow. That's right there. OK. Well without practical example this is not enough. I'm going to give you a practical example in Iowa's VOLP and how this can be useful to practical type casting. So we lessa we have a couple of buttons and messages of view are available in your view controller or your storyboard in your lap button labeled view. But if you think about it as I said they all come. They all share the same fundamental Perens which is what you view here. Right button. Whereas a button a button comes from view as well. Even though they come from you I control you know control comes to you I view you I label and also you my view is just eye view. So what is what you are allowed to do is you're able to do something like this UI components a logging view logging message that all convergence into you view right there and you don't have to specify this as you might view. You don't have to do the sweep is smart. Again just like what we've seen here sweep is smart enough recognizing hey they all shared a fundamental parents. Let's try to combine them together. But casting automatically for us. OK. Well here's a magic solution to what we did here you're able to group them together. Right very handy very portable. Right. And you're able to apply some sort of a setting or some sort of changes to each each object. By downcasting. So going to give you a warning. One example like this I'm just I'm a copy paste because this is not that complicated. So let's say for component in you like components key components and you have an you have an object and you're going to and do something like this if lead button component as you button right does normal type and you can change the background color and title whatever you want to. OK. And also for label you can change the background color of the label. You can turn the font size of label you white label and you can do whatever you want. OK. So when it comes to programming when it comes I was told that you are able to group this unique object into one single basket into one single array. You're easy to carry around. And then if you need to down by upcast thing and also if you want apply specific logic specific attributes to each object all you have to just go through a loop and then be able to use this if let if let downcasting to do what you want to do. OK. Those handy feature. But downcasting upcast is not the most practical way in Iowa's Veltman there's a better way of called. Or into programming. You learn a lot more in later chapters so you guys should get very very excited about this. OK. So and lastly you guys have seen something like this. And also you as if you never use that typecasting before this is wrong. You've been using typecasting a lot in your programming. For example you have something like you storyboard and you have a main program. In I was a little man. Well this can be confusing. Raju Everest's or Ebor main here and then you might have done something like this. Let the story were in view controller with identifer VC. But the problem is if you take a look at these See you the controller it is a is of parents of view controller. So sometimes you have to downcast it to DC in order to have the methods and properties that you want it to have. Right. So Visi is let's say if this is your custom controller that in Hertz from from UI view controller without using this. This is going to just simply be a controller is not your custom view controller that it hurts from UI if you control. OK. So that's why use as that as they right there. OK. That makes sense. You know most people think typecasting applies to classes only that you can go from simple class and low class but that's not the only case. We also learned that Strax also provide typecasting for example string value and value can be made typecasting to any however unnecessary typecasting is now recommended. I was of Alpers. If you started using typecasts and back and forth what happens if you have to use those as keywords as well as if less code becomes much longer than necessary. So if you know how to group things together well and chaplet they will learn how to combine multiple objects using particle board programming. I know you're very upset about that. Well you will get that eventually and I'll see you soon in the next lesson to learned how to create reusable as well as scalable code base by learning about generics you will come out dry not wet. Also known as we enjoy PAETEC.