Learn the Essentials of Swift in one hour

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hello my name is paul and in this video we're going to walk through the fundamentals of swift programming in under one hour it's going to be super fast like lightning if you want to pause the video frequently as you go to follow along or maybe to sit back and watch me talk this video is really aimed at two kinds of people the first kind are people who have finished the introductory days in my 100 days of swift diy course if that's you this will be a review of everything you've learned so far so sit back and have a refresher as we go the second type of person our folks already have lots of experience in other programming languages and they want to get their skills across the swift easily if ideas like arrays dictionaries functions closures protocols and more are comfortable for you already this is the right video for you otherwise perhaps check out my existing 100 days of swift ui course the introductory days there i mentioned already they go through the same stuff much slower lots more detail many more examples to really explain what this stuff does this is the fast version as a refresher only if you're set let's get to it but trust me strap in your ears this is gonna be fast let's start at the beginning swift can make constants and variables but constants are preferred for example i can make a new variable and change its value like this by name equals ted name equals rebecca if you don't want to change a value use let rather than var to make a constant for example let user equals daphne and when you want to know what's inside a variable or constant use the print function passing in a value for example user that'll print out daphne into the xcode area below swift strings start and end with double quotes like this let actor equals tom cruise plus they work with a full range of world languages with no problems including things like emoji just go ahead and add them straight to your string if you want to have double quotes inside your string place a backslash before them like this let quote equals he tapped a sign saying backslash quote believe backslash quote and walked away and what was saying here is these quotes don't actually end the string they're just inside the string if you want a string that spans multiple lines you start and end with three double quotes like this that movie equals quote quote quote a day in the life of an apple engineer quote quote no matter how you make your string swift provides a collection of properties and methods that make them useful to work with for example i could say print actor.count to read how many letters are in the actor string there are also methods like has prefix and has suffix that determine whether a string starts or ends with a substring for example i could say print quote dot has prefix he which will be true it starts with the letters he whereas print quote dot has suffix away dot that'll be false because in swift strings are case sensitive and it starts with a capital a but has a slower case a in the original string swift stores whole numbers using the type int and they support the standard range of mathematical operators for example let's score equals 10 let higher score equal score plus 10. that half score is score divided by two it also supports compound assignment to modify a variable in place for example via counter equals 10 counter plus equals to 5. now integers come with their own functionality for example you could say let number equals 120 print number dot is multiple of three and of course the answer is true three times forty is a hundred and twenty you can also make new integers in a random range of your choosing for example that id equals int dot random in the range one through a thousand so it could be one it could be a thousand or any number in between if you create a number with a decimal point swift will consider it to be a double even if the numbers after the point are zero for example let's score equals 3.1 a double but 3.0 is also a double and this matters because int and double are different data types in swift you cannot mix them by accident swift has a type ball to store either true or false like this let good dogs equals true let game over equals false you can flip a boolean from true to false or vice versa by saying toggle i could do var is saved equals false and it is saved dot toggle you can create strings out of other data by using string interpolation inside your string write a backslash then put your variable or constant name inside parentheses for example i could say let name equals taylor let age equals 26 and now let message equals i'm string interpolation name and i'm string circulation age years old and print message and when this code runs it'll print out i'm taylor and i'm 26 years old you can group items into an array like this var colors is an array of red green and blue or let numbers is an array of 4 8 15 and 16 or val readings is an array of 0.1 0.5 and 0.8 now each of these things are different arrays it's an array of strings here and we have integers here an array of doubles here and this maths because when you read a value you'll get a string int or double depending on the array you read so if i have print colors 0 that'll be a string or print readings 2 that will be a double now be careful when you specify an index like 0 or 2 make sure it exists otherwise your code will crash if your array is variable like colors is you can say append and new value however the value add must match the type of the other items in the array so i'm adding a string here i couldn't add an integer here arrays have a bunch of useful functionality you can use count to read how many items there are or remove at to remove a single item i could say colors dot remove at zero to remove red and then print colors dot count so i should still have three items in there plus you can check whether the array contains an item by using contains i'll do print colors dot contains octarine which ought to be false dictionaries store multiple values using keys we specify for example we can make a new dictionary called employee and in here i'll say the key name is name tailor key name job value singer and when you want to read values back out from the dictionary use the same key name to use when making the dictionary for example i could say print give me the employees job if job doesn't exist give me a default value of unknown in this case job does exist so this will print singer sets are similar to arrays except they can't add duplicate items and they don't store things in a particular order for example i can make a new set of numbers by doing a new set with the array of one one three five seven nine and i print out numbers what we get is basically random so we're gonna get here three five the duplicates gone and the order's gone too if you want to add items to your set use insert i'll insert a number 10 here we don't append because there is no order to append to now sets have one massive advantage over arrays when you say something like numbers contains uh 11 it will run instantly no matter how many items a set has even if it has 10 million items it'll still run basically instantly and enum is a set of named values we can use that makes our code safer and more efficient for example i can make a new enum called weekday and give this one case for every weekday in the week i'll do monday tuesday wednesday thursday and friday i can now make a new instance of the enum by saying var day equals weekday dot monday and assign it by doing day equals dot friday you can try to force a specific type on a variable or constant using type annotation for example i could say far score double equals zero now without the colon double part swift would imagine this was an integer we're saying no this is actually a double let's look at some existing type annotations the types you've seen so far we could say let player string equals roy or let lucky number int equals 13 or let pi double equals 3.141 or var is enabled bull equals true or var albums be an array of strings and i'll do this equal to red and fearless or via user is a dictionary with string for the keys and string for the values equal to id colon at two straws we'll have a set as well we'll do var books is a set of strings equal to a set the bluest i and foundation now arrays and dictionaries these two here are so common they have special syntax that's easier to write we can actually just say brackets around string and here with dictionary it's string colon string like that it's just shorter otherwise it means the same thing now knowing the exact types of data like this is particularly important when you want to make empty collections for example we could make an empty array like this by teams an array of string equals a new array of strings or remove type annotation entirely and say var clues equals a new array of string like that values of enums have the same type as the enum so if i had enum ui style case light dark and system i could save our style is a ui style equal to dot light use if else if and else to check a variety of conditions and run code as appropriate for example i could say let age equal 16 if age is less than 12 print you can't vote else if age is less than 18 i'll do print you can vote soon else all of the values print you can vote now now we can use ampersand ampersand to combine conditions together both must be true in order for the whole thing to be true i could say let temp equals 26 if temp is greater than 20 and temp is less than 30 print it's a nice day alternatively if you use pipe pipe you get ore when if either one of those two things is true the condition is true swift can check a value against multiple conditions using switch for example i could say switch on forecast if the case is dot sun print it's a nice day if the case is dot rain print uh pack an umbrella for all other values default our print should be okay now switch statements must be exhaustive in swift you must have one case for each value on your enum or have a default case to handle any other kind of value which is important for things like strings integers and more the ternary conditional operator checks the condition and returns either one item or the other depending on the result of that condition for example i could say let age equals 18 let can vote be if age is greater equal to 18 send back yes otherwise send back no and when this code runs canva will be set to yes because age is at least 18. swift's for loop runs some code once for every item in an array set or dictionary or across a fixed range of numbers for example i could say let platforms is an array of ios mac os tv os and watch os and then say for os in platforms print swift works on os like that you can also loop over a range of numbers something like for i in 1 through 12 print 5xi is five star i get the five times table printed out that thing there one dot dot 12 means from 1 to 12 inclusive of 1 and 12 if you want to count to 11 you could do one dot dot less than up to but excluding the final number and if you want to exclude the loop variable entirely just ignore it use underscore instead for example i could say var lyric equals haters gunner and then for underscore in one through five lyric plus equals to hate and now print lyric to get a nice taylor swift shake off lyric right here in swift there we go there are also while loops give these things a condition and they'll run their loop body for as long as the condition is true for example we could say var count is ten while count is greater than zero print count dot dot dot and then count minus equals one and then when the loop finishes print go that'll count down from 10 to 1 then print go you can if you want to use continue to skip a particular iteration of a loop and go to the next iteration for example i could say let files equals an array of me dot jpeg and then work.txt and then sophie.jpg and now for file in files if file has suffix.jpg is false it's not a jpeg continue go to the next file if we're still here we'll print out found picture file alternatively you can use break to skip the remaining iteration and all future iterations as well it'll exit the loop immediately to make a new function write func then your function name then parameters in parentheses for example i could say func print times table for number int then for i in 1 through 12 print let's do i x number is i star number and now i can say print times table number eight let's get the eight times table now notice how i've got to say number colon eight at the call site the parameter is part of the function call itself when you want to return data from a function tell swift what type it is then use return to send data back for example we could make a function to do a dice roll func roll dice returns int and then do return in dot random in the range one through six and now let result equals roll dice and then print result now here as our function contains only a single line of code returns our value you can actually remove the return keyword entirely and just have in dot random in tuples store a fixed number of items of specific types which is really convenient for returning multiple values from a function for example i could say funk getuser returns a tuple with first name being a string and last name being a string then inside there i'll send back first name is taylor and last name is swift when i call it i can say let user equals get user and now print out name is user.firstname user dot last name i can read those tuple values directly now if you don't need all the values from a tuple you can destructure it you can put it apart into individual variables or constants and then optionally ignore the ones you don't want using underscore for example i could have said let first name underscore be getuser and now i don't get access to the last name and first name is a constant all by itself if you don't want to pass a parameter's name into a function put an underscore before it for example func is uppercase underscore string string returns bool and we'll say string is equal to string to uppercase i'll make a new string like uh hello world and that result to be is uppercase string so there's no parameter name at the coresight anymore an alternative is to write a second name before the name one for external use one for internal use for example i could say funk print times table for number int this will do 4 i in 1 through 12 print i x number is i star number now the course site i say print times table four five so four is used externally a number is used internally four comes first number comes second we can provide default values for parameters by writing an equals after their type name then given the value for example i can have a function called greet some kind of person string and will it be a formal greeting and not a boolean equal to false by default so i'll say if it's formal print welcome person otherwise we'll just do print hi person and now when we call greet we can call it with formal or without if i want to greet tim formally i can do or i could just greet taylor and formal will be false by default because that's what we've asked for to handle errors and functions you've got to first define the kinds of errors that can occur second write a function that throws one or more of those errors and third call that function and handle its errors appropriately first make a new enum to store password errors it conforms to swift's built-in error type this has two password errors it's too short or it's too obvious now write a new function called check password that accept a password string i'll say it's able to throw errors and will return a string if the password count is less than 5 it's not good enough we'll throw password error dot short if the password is equal to one two three four five then we'll throw password error dot obvious if we're still here then let's take the password if the count is less than ten we'll return okay else all other lengths will return good now we want to call the throwing function we'll say do let result scroll down equals try check password one two three four five and print out the rating is result and now catch errors if something goes wrong this line will not be run it'll jump to one of our catch blocks instead i'll catch the error password error dot obvious and print out uh i have the same combination on my luggage then a generic catch all at the end print there was an error boom let's press play and it'll print out i have it on my luggage now when it comes to catching errors you must always have a generic catch-all at the end like this one that'll catch any kind of error at all you can assign functionality directly to a constant or variable like this let's say hello equals open brace print hi there and now you can call say hello like a regular function just by saying say hello open and close parens and i'll print out hi there now in this code say hello is a closure it's a chunk of code we can pass around and call whenever we want to if you want to accept parameters place them inside the brace for example name string return string in and now i can say return hi name like that now here the in keyword marks the end of the segment with our parameters and return type everything after in is the body of our closure itself the actual function code we want to run now closures are used extensively in swift for example there's an array method called filter which runs all the elements of an array through a test we provide as a function and all the ones that pass the test go into a new array that's sent back for us to use we can provide this test using a closure for example you'll have an array of names and filter out all the ones that don't begin with t let's say let team equals an array of gloria suzanne tiffany and tasha then we'll say let only t all the t names be team.filter and i'll pass in name string returns bull in this is our closure return name dot has prefix t and print out only t and now print out just tiffany and tasha the only two names that begin with t so inside the closure we list the parameter we receive from filter and name strings coming in and say what's going back a boolean true or false then write in and everything after in is the main body of our closure itself swift has a few tricks up its sleeve to make clojures easier to read for example this closure has only one line of code and so we can remove the return keyword second up we know that filter must receive one item from the array in our case a name string it'll pass it through a test and always return a boolean true if it passed test false otherwise it must work that way it must take one item from the array one string and return true or false swift knows that and so we can remove the return type entirely in fact we can remove the parameter type entirely as well there's got to be a string and just say name in but we can go further using special syntax called trailing closure syntax which looks like this remove the opening brands and remove the closing parens too just go ahead and launch into a closure straight away after calling filter finally if you want to swiftman can provide for us short parameter names such as dollar 0.1.2 and so forth so we don't even have to write name in in this case we just use dollar zero dot has prefix at which point the whole thing fits on a single line of code it is quite beautiful structs let us make our own custom data types complete with our own properties and methods for example i can make a struct called album it'll have a title string it'll have an artist string and is released boolean set the true by default we'll also add a print summary method this thing will do print title by artist we can now go ahead and make one let red is a new artist sorry album not artist with a title of red artist of taylor swift and print red dot title and red dot print summary like that now we make one of our custom structs we're using what's called an initializer swift basically lets us treat the thing as if it were a function call passing in a parameter for each one of the properties we have inside the struct it actually slightly makes this for us and it's called a member wise initializer once each of the member properties it has inside there now if you want to have a struct method change one of its properties you must mark as mutating mutating func remove from sale is released equals false a computed property calculates its value every time it's accessed we can add one here to our employee struct like this var vacation remaining is an int and send back vacation allowed minus vacation taken so we're not having a stored value in there it's calculated dynamically every time vacation remaining is called that is now get only we can't modify that if you want to modify it you want to say this is the getter and below provide a setter what to do when we try and set this value in our case we'll set vacation allowed to be vacation taken plus new value and new values provided by swift and stores whatever value the user was trying to assign to this property property observers are pieces of code that runs when a property changes there are two to choose from this set is called after the change has taken place and will set called before the change is taking place we could demonstrate this by adding a new did set observer to this score property so whenever it changes we'll print a new value out so we'll open a brace then say did set print score is now score and when this code runs it will add and subtract and print out the change as it happens initializers are special functions that run when a new instance of a struct is created it must make sure that all properties inside the struct have a value by the time it finishes now swift will make one of these automatically for your structs called the member wise initializer but sometimes you can make your own to have custom control for example i might have one here init with a name string and no number int i'll say assign name the parameter to our local property and for number i'll pick a random one but in the range of 1 through 99 now be careful when you have your initializer here you don't put func before the init and you never explicitly return a type it always implicitly returns a type of its struct in this case a player swift has several options for access control inside structs there are four that are most common the first is private which means let nothing outside the struct read or write this the second is private set which means something outside can read it only internal things can write it then there's file private which means anything inside the current file can read and write it and third there's public which means let anyone anywhere read or write this as an example if we had a struct call bank account we could have a variable in here funds equal to zero with mutating func deposit some amount integer and we'll do funds plus equals to amount then we might have mutating func withdraw amount int returns a ball and if funds are greater than amount subtract from funds amount and return true it all worked otherwise returned false now right now fund is available to everyone to read and write which means they can bypass our logic in the withdrawal method making it rather pointless however if we modify this to have access control private set it means we can make a bank account down here uh bank account equals a bank account with funds of 100 and now we can read funds but we can't write funds so printing out will work but uh adding a thousand to it whatever will not work that'll give me a big swift error when i press play swift support static properties and methods allowing us to add them directly to a struct type rather than to a particular instance of a struct for example i might have a struct called app data with a static let version string equal to 1.3 beta 2 or i might have static settings file be equal to settings.json and now everywhere i want to read these values log files diagnostics support emails about screens who knows what i can just do print app data dot version and read that directly rather than making a new app data and trying to read that instance's value classes let us create custom data types like structs but they're different from structs in five key ways first up when we make a class we can make inherit from or build upon another existing class it'll gain all the properties and methods of that parent class for example i could say as a class called employee with an hours int property an initializer takes an hour's int and copies it into the property like that plus a print summary method which prints i work hours hours a day we can now make a new class called developer based upon employee so gain its property and its methods in here add a new method called work which is saying a print out i'm coding for hours hours a day well then make an instance of developer let naval equals a developer with hours eight noval.work and noval dot print summary so we're using methods from the developer class but also from the parent class the superclass employee now if a child class like developer wants to change a method it got from the parent class we must use the override keyword like this override func print summary inside here i'll do print i spend hours hours a day fighting over tabs versus spaces that's the first difference the second difference is that swift will never make a generated initializer for our classes this is because initialization for classes is much trickier than structs and if we boil it right down to the simplified possible rules really there are just three points firstly as i said you'll never have a member-wise initializer made for us like would have restructs so you've got to write your own which leads to if you give any child class a custom initializer it must always call the parent initializer after it's finished configuring its own properties and third if a subclass has no custom initializers it'll automatically inherit all those from its parent for example i could say there's a class called vehicle let is electric be a bull and then knit is electric bull self is electric equals is electric we'll inherit a new class called car from vehicle and this will have one new property called is convertible a ball and the initializer for this has to accept a value for is convertible but also for vehicles is electric so i'll say init is electric bull is convertible bull we'll copy that into our local property first but then critically we've got to call up to the superclass the parent class vehicle telling it its value for is electric so we'll call super.init is electric is electric so super let us call up the methods and initializes inside our parent class as needed the third difference is that all copies of a class share one particular set of data meaning if you change one instance all copies of that instance are also updated for example if i had class actor var name equals nicolas cage like this and then make an instance of actor for actor one equals a new actor and var actor two will be a copy of actor one when i change actor two's name to be tom cruise and then print out actor one dot name and print actor two dot name you're gonna see they are both tom cruise they both point to the same piece of data this is not the same for struct structs never share their data if i had made this struct actor then we'd have nicolas cage and tom cruise printed separately the fourth difference is that classes can have a d initializer if they need to when the last reference an object is destroyed this will be run automatically by a system for example we can make a class that prints a message when it's created and destroyed let's say class site let id int init id int self.id is id and then print out when it's made site id i've been come on created and then i'll add a d initializer afterwards when it's been destroyed and we'll print uh come on hudson site id i've been destroyed like that what we're saying here is when we're creating one of these things print a message when i'm de-initializing it when destroying it print a message so now let's go ahead and loop from i in one through three let's cite eagles a new site with id of i and then print out uh site site.id i'm in control let's go ahead and run that code now and you'll see that site 1 is created in control and then destroyed and then site 2 created control destroyed site 3 created control and destroyed so it's destroyed as soon as the loop iteration finishes and a d initializer is called the final difference is that classes let us change variable properties even in the class instance itself is constant for example if i want to say there is a class of singer with a name of adele i could say let singer equal singer and then singer dot name scroll down slightly equals justin and print singer dot name and that will work fine i can change that even though the instance itself is constant the property inside it is not as a result of this classes don't need to have the mutating keyword in front of methods that change properties you can always do it protocols define functionality we expect other types to support and swift will ensure they follow the rules correctly for example we could define a vehicle protocol like this protocol vehicle and i'll say to be a vehicle you could have one method called estimate time for distance int returning an int and also another one called travel distance int that lists the required methods that for this protocol to work but there's no code inside there there's no bodies to those functions we're specifying only the names parameters return types and more now once you have a protocol you can make other types conform to it by implementing the required functionality for example we could make a new struct called car that conforms to the vehicle protocol and inside there i'll have estimate time for distance and swift completes it nicely because it knows we're conforming to the protocol i'll do distance divided by 50 and then func travel listens i'll do print i'm driving distance km now all the methods inside the vehicle protocol must exist inside the conforming types with the same name same parameter types same return type and more you can of course add other ones i could have in here you know funk open sunroof print it's a nice day because the protocol specifies only the minimum functionality not the complete functionality once we have a protocol in place we can write a function that accepts any kind of vehicle car bike airplane whatever as long as it conforms to vehicle we know it's safe swift nose implements estimate time for distance and travel distance so i could say let's do funk commute distance int using vehicle vehicle some kind of vehicle inside here we'll say if vehicle dot estimate time for that distance is greater than 100 i'll print too slow otherwise we'll do vehicle dot travel that distance i can even though it accepts any kind of vehicle i can call it with specific types like a bike or a car or whatever i could say let car equals a new car commute distance 100 using that car see how it looks boom works correctly protocols can also require properties so we can require properties for how many seats vehicles have and how many passengers they have currently and so forth up here we could say var name will be a string get oops get and var current passengers will be an int that is get and set so this adds two properties one called name which must be a string and it's marked get meaning that it might be a constant or a computed property current passengers must be an integer and it's marked get set read and write it might be a variable or a computer property with a getter and a setter and now all conforming types must add those two properties i say in here let name equals car or var current passengers equals 1. now if you want you can conform to multiple protocols if you need to just list them out a comma b comma c comma d up here now if you want to sub class another class and conform to properties put your class name first then comma then protocol a comma b comma c comma d extensions let us add new functionality to any kind of type maybe ones we've made or maybe apple's own ones for example strings have a method in place to trim white space from the start and end of a string but it's pretty wordy so we could use an extension to make it shorter like this extension on string funk trimmed returns a new string inside there we'll call self dot trimming characters in dot white space in new lines and how to use it we'll make a string like this one by quote equals space base space the truth is rarely pure and never simple space base space and let trimmed equals quote dot trimmed now if you want to change the value directly inside the method rather returning a new value you want to mark it as mutating for example we could do this mutating func trim don't return a string it in place and inside there we'll do self equal self dot trimmed so trim ourselves using the previous method and assign it back to our self and because quote here is variable we can say quote dot trim to get it trimmed now extensions can also add computed properties to types for example we could say on strings again i want to get the lines inside a string as an array of strings i could say var lines is an array of strings and you self dot components separated by dot new lines now this method here component separated by splits a string into an array of strings based on the boundary of our choosing in this case is line breaks we can now use that with a multi-line string let lyrics equals quote quote quote but i keep cruising can't stop won't stop moving quote quote quote and then print out lyrics.lines.count which should print out two because it has two lines right now protocol extensions let us add computed properties and methods to a whole protocol so any type conforming to the protocol get access to them for example arrays dictionaries and sets all conform to a common protocol called collection and so we can add a computed property to that so all three of them will gain access to it we'll do extension on collection var is not empty is a bull now send back is empty is equal to false and now you can put it to use let guests equals an array of mario luigi and peach if guests dot is not empty print guest count is guests.count this tiny extension exists in many many thousands of swift projects it's that useful this approach of extending collections means we can add required methods in the protocol itself you must add a b and c but then add default implementations of those methods inside a protocol extension and all conforming types for our protocol will get access to our default implementation or they can override them in their own structs optionals represent the absence of data for example it's the difference between an integer holding the value of zero and holding nothing at all for example in this code here we've got a string string dictionary with key strings mario and luigi what would happen if i said make peach opposite equal to opposites of peach now this attempts to read the value belonging to the key peach which does not exist so peach opposite can't be a regular string it's not there swift's solution is called optionals and means data that might be there or might not in this case peach opposite is an optional string a string question mark that is type optional string it might be there or it might have nothing at all a special value known as nil any kind of data can be optional optional string optional int optional double optional array optional bool they all work as well as enums structs and classes now swift won't let us use optional data directly it just won't because it might be empty that means we've got to look inside the optional a process called unwrapping the optional we look inside see if there's a value if there is take it out and use the value somehow now swift gives us various ways of unwrapping optionals because it's very common but the one you'll see most looks like this if let mario opposite equals opposites of mario then print mario's opposite is mario opposite like that so this thing here is going to read the optional value from our dictionary and if it has a string inside which it does it'll be taken out of the optional and placed into mario opposite and it's not optional anymore and this constant is available inside the braces right here as a non-optional string and we can use it with the print call swift has a second way of unwrapping optionals called guard let this is very similar to iflett but it flips things around whereas if let runs a cope between its braces if the optional has a value i.e it's not nil guard let does the opposite it runs a code between its braces if the optional does not have a value here's how it looks like a new function called print square of number and optional int it could be a million or zero minus a million or nil nothing at all now we can only square numbers that have actual values so the first thing we'll do is check there's a real number in there we'll unwrap it using guard let guard let number equals number else print missing input and return if we're here we can now use number as a non-optional integer so i'll do print number x number is number star number like that now if you use guard in this way to check a function's inputs are valid then swift requires you to exit the function if your test fails and so if number was empty i have to have return here if i don't have return here swift will complain very loudly indeed no you can't do that you must exit the current scope which right now is a function however if the optional did have a value inside like we have here it's available after the guard finishes that's why i can refer to number in all these places as a non-optional integer here's a tip for you guard works with any condition including ones that don't unwrap optionals for example guard some array dot is empty else return believe it or not swift has a third way of unwrapping optionals called the nil coalescing operator it'll unwrap the optional but if it's empty it'll let you provide a default value instead here's how it looks let tv shows equals an array of archer babylon 5 and ted lasso now if we read a random element from that using the random element method of arrays will get back an optional string because the array could have been empty so we'll say let favorite equals tv shows dot random element but i don't want a random element i always want a real string back so i'll use a nil coalescing operator question mark question mark with none so we always get a real string back now this operator is really useful in all the places where optionals appear for example making an integer from a string returns an optional integer because you might have provided fish rather than 5 an invalid number here we can use nil coalescing to provide a sensible default integer for example let input equals an empty string not a valid number let number equals an int of that input nil coalescing 0 and now print out number and because that test will fail this is not a bad integer it'll be set to zero our default value and print out down at the bottom optional training reads optionals inside optionals like this let names equals an array of arya bran rob and sansa then let chosen equals names dot random element question mark dot uppercased and now print out next in line is either chosen nil coalescing or no one like that now when that code runs it'll pick a random name in this case it's pricked arya named my dogs um but it went wrong it'd print no one but notice how it's uppercased that is nil coalescing in action it's right here on line four this question mark followed by more code it allows to say if the optional has a value inside then whatever some more code in our case we're saying if random element returned a valid string then uppercase it when calling a function that might throw errors we can use an optional try try question mark to convert any errors into optional nil and success into an optional with the value inside here's how it looks first up as usual make a new error type i have a user error that conforms to swift error protocol i'll then say there are two errors bad id and network failed we'll then make a function that throws errors so i'll say get user with an id int can throw errors returns a string and will immediately just testing purposes throw user error dot network failed and now we want to call get user we don't care what comes back we just care did it work or did it not work we can do that by saying if let user equals try question mark get user id 23 print user is user and so the get user function will always throw an error in this case network failed but we don't actually care what was thrown all we care was did we get a user back or not if you want to know exactly which error came back you can't use try question mark you've got to use do try and catch instead we've covered the majority of swift language fundamentals in this one very very fast video but we've only scratched the surface of what swift can do if you want to carry on learning there's stacks more of swift language features to learn but i'd recommend against it just yet despite i'm sure there being commenters lining up below to ask why i didn't mention their favorite swift language feature i'm saying to stop for a reason you know enough now to go and build real apps good apps with swift and swifty y learn and practice what you have right now and then if you want to come back and learn some more and more and more and more but first put into practice what you have and if you want you can follow my free 100 days of swift ui course it's all on youtube or on my site with tests and more it walks you through building fantastic ios apps from scratch with the skills covered in this video if you like this video please press like or subscribe to the channel even better and yes if you want to tell me why did i miss off enum associated values whatever go ahead and mention in the comments below and i'll try and read them take care folks well done for making it through this very long very fast and quite hard video in places your reward is a chance to see my dog arya this is one of the two sammy heads i have uh she can have some treats because she's been a very good girl let me record this full hour of swift stuff without interruption here you go one for you uh she loves to come in while i'm recording and woo or bark or just stare at me silently until she gets some treats and fortunately she gave me a whole hour of difficult recording without interrupting teamwork so she's been a very very good girl and she can have some treats i do have two sammy heads the other one luna isn't quite so smart this one listens to me talking in a closed room and knows uh-huh it's recording time that means i can get some treats oh the other one's just arrived the other one heard and it's coming now otherwise obviously getting smarter over time there you go aria you eat that one good girl oh lula come on you can get a treat too everyone see you come on up here there we go another dog i'll treat two they are good dogs really you
Info
Channel: Paul Hudson
Views: 52,161
Rating: undefined out of 5
Keywords:
Id: n5X_V81OYnQ
Channel Id: undefined
Length: 58min 14sec (3494 seconds)
Published: Fri Oct 15 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.