Swift programming big nerd ranch pdf download






















When the loop is entered, the initialization expression is evaluated to set up the iterator for the loop. The condition expression is evaluated. If it is false, the loop is ended and execution of the code is transferred to after the loop. After the code between the braces is executed, the increment expression is executed. Depending on the code, the incrementer can be increased or decreased. Once the incrementer is set, step 2 is repeated to determine whether the loop should continue iterating.

Refactor the implementation of the for-in loop from the beginning of this chapter to use the more traditional form. For example, instead of incrementing i by 1 at each pass of the loop, you could instead increment by 3, or do something entirely different.

For example, imagine a simple space shooter game with a spaceship that continuously fires its blasters so long as the spaceship has shields. But if the shields have a value greater than 0, the blasters will keep shooting. The code snippet below illustrates a simplified implementation of this idea. The repeat-while loop is called a do-while loop in other languages. The difference between while and repeat-while loops is when they evaluate their condition.

The while loop evaluates its condition before stepping into the loop. This means that the while loop may not ever execute, because its condition could be false when it is first evaluated. The repeat- while loop, on the other hand, executes its loop at least once, and then evaluates its condition. The syntax for the repeat-while loop demonstrates this difference. Thus, the repeat- while loop ensures that the spaceship fires its blasters at least one time. The repeat-while loop avoids a somewhat depressing scenario: What if the spaceship is created and, by some freak accident, immediately loses all of its shields?

Perhaps it spawns in front of an oncoming asteroid. It would not even get to fire a shot. That would be a pretty poor user experience.

A repeat-while loop ensures that the blasters fire at least once to avoid this anticlimactic scenario. Recall from Chapter 5 where you used fallthrough and break that control transfer statements change the typical order of execution.

In the context of a loop, you can control whether execution iterates to the top of the loop or leaves the loop altogether.

You are going to use the continue control transfer statement to stop the loop where it is and begin again from the top. The first if statement checks whether the blasters are overheating, and the second checks the fire count. For the first, if the blasters are overheating, a number of code steps execute. You next log that the blasters are ready to fire again after waiting for 1 more second, which you do simply because it makes it easier to see what logs to the console next , set blastersOverheating to be equal to false, and also reset blasterFireCount to 0.

The second if statement checks whether blasterFireCount is greater than If this conditional evaluates to true, you set the Boolean for blastersOverheating to be true. At this point, the blasters are overheated, so you need a way to jump back up to the top of the loop so that the spaceship does not fire.

You use continue to do this. If the second conditional is evaluated to be false, you log to the console as before.

Next, you increment the blasterFireCount by one. After you increment this variable, the loop will jump back up to the top, evaluate the condition, and either iterate again or hand off the flow of execution to the line immediately after the closing brace of the loop. There is nothing to change the value of WOW! If nothing changes, and your computer has enough power to run forever, this loop will continue to execute. This is what we call an infinite loop. But all games must come to an end.

To exit the loop, you will use the break control transfer statement. You are a pretty good shot, apparently. Next, you add a new if statement that checks whether the spaceDemonsDestroyed variable is equal to If it is, you log victory to the console.

Note the use of break. The break control transfer statement will exit the while loop, and execution will pick up on the line immediately after the closing brace of the loop. This makes sense: if the user has destroyed space demons and the game is won, the blasters do not need to fire anymore.

Use another loop to make sure the first loop is run 5 times. Hint: one good way to do this is to use a nested loop. You have seen and used strings already.

Like all strings, it can be thought of as an ordered collection of characters. In this chapter, you will see more of what strings can do. Create a new playground called Strings. Listing 7. This instance was created with the let keyword, making it a constant. Recall that being a constant means that the instance cannot be changed. If you do try to change it, the compiler will give you an error. Create a new string, but make this instance mutable. In other words, you can change the contents of this string.

Use the addition and assignment operator to add some final punctuation. You should see that the instance has changed to "Hello, mutable playground! Loop through the mutablePlayground string to see the Character type in action. In it, you access the characters property of the String mutablePlayground. Do not worry about what a property is right now; this topic will be covered in detail in Chapter For now, all you need to know is that a property is a way a type holds on to data.

In Swift, you access properties via dot syntax, as in mutablePlayground. Every character is logged to the console on its own line because print prints a line break after logging its content. Reveal the console. Your output should look like Figure 7. Figure 7.

Unicode represents human language and other forms of communication like emoji on computers. Every character in the standard is assigned a unique number. Nonetheless, it is good to have an understanding of how these types work with Unicode. Having this knowledge will likely save you some time and frustration in the future. Unicode scalars At their heart, strings in Swift are composed of Unicode scalars.

Unicode scalars are bit numbers that represent a specific character in the Unicode standard. The 1F60E portion is a number written in hexadecimal, or base Create a constant to see how to use specific Unicode scalars in Swift and the playground.

The quotation marks are familiar, but what is inside them is not a string literal, as you have seen before.

It does not match the results in the sidebar Figure 7. In this case, oneCoolDude is assigned to be equal to the character representing the sunglasses-wearing emoji. How does this relate to more familiar strings? It turns out that every string in Swift is composed of Unicode scalars. So why do they look unfamiliar? To explain, we need to discuss a few more concepts.

Every character in Swift is built up from one or more Unicode scalars. One Unicode scalar maps onto one fundamental character in a given language. This scalar is placed on top of — that is, combined with — the character that precedes it. Every character in Swift is an extended grapheme cluster. Extended grapheme clusters are sequences of one or more Unicode scalars that combine to produce a single human- readable character.

Making characters extended grapheme clusters gives Swift flexibility in dealing with complex script characters. For example, you can see all of the Unicode scalars that Swift uses to create the instance of String named playground that you created earlier using the unicodeScalars property, which holds all of the scalars that Swift uses to make the string. You should see the following output: 72 44 32 97 What do all of these numbers mean? Recall that the unicodeScalars property holds on to data representing all of the Unicode scalars used to create the string instance playground.

Each number on the console corresponds to a Unicode scalar representing a single character in the string. But they are not the hexadecimal Unicode numbers.

Instead, each is represented as an unsigned bit integer. Canonical equivalence While there is a role for combining scalars, Unicode also provides already-combined forms for some common characters.

You do not actually need to decompose it into its two parts: the letter and the accent. Create a new constant string that uses this Unicode scalar.

Why does Swift say that they are equivalent? The answer is canonical equivalence. Canonical equivalence refers to whether two sequences of Unicode scalars are the same linguistically. Two characters, or two strings, are considered equal if they have the same linguistic meaning and appearance, regardless of whether they are built from the same Unicode scalars. The fact that they were created with different Unicode scalars does not affect this.

Counting elements Canonical equivalence has implications for counting elements of a string. You might think that aAcute and aAcutePrecomposed would have different character counts.

Write the following code to check. The results sidebar reveals that the character counts are the same: both are 1 character long. Canonical equivalence means that whether you use a combining scalar or a precomposed scalar, the result is treated as a single character. In general, the brackets [] indicate that you are using a subscript in Swift.

Subscripts allow you to retrieve a specific value within a collection. The code above WOW! You will learn more about subscripts below, and will also see them in action in Chapter 9 and Chapter 10 on arrays and dictionaries.

This limitation has to do with the way Swift strings and characters are stored. You cannot index a string with an integer because Swift does not know which Unicode scalar corresponds to a given index without stepping through every preceding character. This operation can be expensive. Therefore, Swift forces you to be more explicit. Swift uses a type called String.

Index to keep track of indices. Do not worry about the. Index; it just means that Index is a type that is defined on String to help manage indices. This property yields the starting index of a string as a String. Say you want to know the fifth character of the playground string that you created at the beginning of this chapter.

This property yields an instance of type String. Next, you create a constant to hold onto the position within the string to which you would like to advance.

The result is a String. Ranges, like indices, depend upon the String. Index type. Imagine that you wanted to grab the first five characters of playground.

You can use the same fromStart and end constants. Index, but it works similarly to the range you saw in Chapter 6 for the range 1…5. You used this new range as a subscript on the playground string. This subscript grabbed the first five characters from playground. The result is that firstFive is a constant equal to "Hello". You can find the appropriate codes on the Internet. When you see an optional, you know one of two things about that instance: either it has a value and it is ready for use, or it has no value.

If an instance has no value associated with it, we say that it is nil. You can use optionals with any type to signal that an instance is potentially nil. This feature distinguishes Swift from Objective-C, which only allows objects to be nil. This chapter covers how to declare optional types, how to use optional binding to check whether an optional is nil and make use of its value if it has one, and how to use optional chaining to query a sequence of optional values.

An instance that may potentially be nil should be declared to be an optional type. This means that if an instance is not declared as an optional type, this instance is guaranteed to not be nil.

This way, the compiler knows whether an instance can be nil. This explicit declaration makes your code more expressive and safe. Create a new playground and name it Optionals. Enter the code snippet below. Listing 8. Next, you explicitly declare the type of errorCodeString to be String — but in a slightly different way than what you have done before.

This time you put a? Now that you have declared an optional and given it a value, log the value of the optional to the console. What would happen if you did not give errorCodeString a value? Try it! Comment out the line assigning a value to errorCodeString. But logging nil to the console is not very helpful. Instead, you want to know when your variables are nil so that you can execute code based on whether there is a value.

Add the following code to your playground. You set up a conditional with code that executes if errorCodeString is not nil remember that! Next, you created a new constant called theError to hold the value of errorCodeString. To do this, you appended! The exclamation mark here does what is called forced unwrapping.

Forced unwrapping accesses the underlying value of the optional, which allows you to grab "" and assign it to the constant theError. That is, the! There is some danger in forced unwrapping. If there is no value inside the optional, your program will crash at runtime. In this case, you checked to make sure that errorCodeString was not nil, so force-unwrapping it was not dangerous. Nonetheless, we suggest that you use force-unwrapping cautiously and sparingly.

The value of theError would still have been logged to the console correctly. The answer requires a better understanding of the optional type. If you had omitted the exclamation mark at the end of errorCodeString, you would have simply assigned the optional String to a constant instead of the actual String value for the error code.

The optional errorCodeString was nil when it was first declared because it was given no value. In the next line, you assigned "" to errorCodeString. You can compare an optional value to nil to determine whether it contains a value. In the code above, you first check whether errorCodeString has a value; if the value is not equal to nil, you know it is safe to unwrap errorCodeString.

Creating a constant inside the conditional is a little clunky. It is called optional binding. This can make your code more concise while also retaining its expressive nature. The constant theError moves from the body of the conditional to its first line.

This makes theError a temporary constant that is available within the first branch of the conditional. In other words, if there is a value within the optional, then a temporary constant is made available for use in the block of code that is executed if the condition is evaluated as true. Also, you no longer forcibly unwrap the optional.

Finally, note that you could have declared theError with the var keyword if you needed to manipulate the value inside the first branch of the conditional. Imagine that you wanted to convert errorCodeString to its corresponding integer representation.

You could accomplish this by nesting if let bindings. Doing so makes theError available to use in the second optional binding. Here, you use a syntax that you saw in Chapter 4 to convert between integer types.

Therefore, Int theError returns an optional, in case a corresponding Int is not found for the given string. The result of Int theError is unwrapped and assigned to errorCodeInteger in the second binding.

Doing so makes the integer value available for use. You can then use both of these new constants in a call to print to log them to the console. Nesting optional binding can be convoluted. While it is not too bad with just a couple of optionals, you can imagine how complicated this strategy can get if you have several more optionals that need unwrapping.

Thankfully, you can unwrap multiple optionals in a single if let binding. This feature helps to avoid the need for nesting multiple if let calls, avoiding nasty code like you saw above and worse.

Next, errorCodeString is unwrapped, and its value is given to theError. You use Int theError to try to convert theError in an Int. Because this results in an optional, you next unwrap that optional and bind its value to errorCodeInteger. If either of these bindings return nil, then the success block of the conditional will not execute. In this case, errorCodeString has a value and the theError can be successfully unwrapped because theError can be converted into an integer.

Optional binding can even take a where clause that works very similarly to what you saw in Chapter 5. Imagine that you only care about an error code if the value is A where clause can help you to focus on the values that you deem important. The where clause is only executed if both optionals are successfully unwrapped. Since theError is "", and that string can be converted to the integer , all conditions are met and the value is logged to the console.

Implicitly unwrapped optionals are like regular optional types, but with one important difference: you do not need to unwrap them. How is that the case? It has to do with how you declare them. Take a look at the code below, which refactors the example above to work with an implicitly unwrapped optional. The conditional is removed because using an implicitly unwrapped optional signifies a great deal more confidence than its more humble counterpart. Indeed, much of the power and flexibility associated with the implicitly unwrapped optional is related to the idea that you do not need to unwrap it to access its value.

Note, however, that this power and flexibility comes with some danger: accessing the value of an implicitly unwrapped optional will result in a runtime error if it does not have a value. For this reason, we suggest that you do not use the implicitly unwrapped optional if you believe that the instance has any chance of becoming nil. Using implicitly unwrapped optionals is best limited to somewhat special cases.

As we indicated, the primary case concerns class initialization, which we will discuss in detail in Chapter For now, you know enough of the basics of implicitly unwrapped optionals to understand what is going on if you find them in the wild.

If each optional in the chain contains a value, then the call to each succeeds, and the entire query chain will return an optional of the expected type. If any optional in the query chain is nil, then the entire chain will return nil.

Imagine that your app has a custom error code for some reason. If you encounter a , you actually want to use your customized error code instead. Afterward, you will want to add some more descriptive text to an error description you will display to the user.

Add the following to your playground. Inside of the if-let success block, you created a new interpolated string and assigned that instance to errorDescription. Last, you added some more informative text about the error. Next, you used optional chaining to create a new instance of the error description to be in all uppercase text, perhaps to indicate its urgency. This instance is called upCaseErrorDescription.

The question mark appended to the end of errorDescription signals that this line of code initiates the optional chaining process. If there is no value in errorDescription, then there is no string to uppercase. In that case, upCaseErrorDescription would be set to nil. This point demonstrates that optional chaining will return an optional. Because errorDescription does have a value in it, you uppercased the description and reassigned that new value to upCaseErrorDescription.

In this case, all we wanted to do was update a string inside of an optional. We did not need anything returned. If there was a value inside of the optional, then we wanted to add some text to the string.

If there was no value, then we did not want to do anything. This is exactly what modifying an optional in place does. If upCaseErrorDescription were nil, then the optional would not have been modified because no value existed to update. It is worth mentioning that you can also use the!

This operation would forcibly unwrap the optional — which can be dangerous, as you have learned. As you have read above, it is best to use? You could accomplish this with optional binding. This can be solved via the nil coalescing operator:??. If the lefthand side optional is nil,?? If the lefthand side optional is not nil,?? You learned a lot of new material. Optionals are a new topic regardless of your level of experience in Mac or iOS development. They are also a powerful feature of Swift.

As a developer, you will often need to represent nil in an instance. Optionals help you keep track of whether instances are nil and provide a mechanism to respond appropriately.

If optionals do not quite feel comfortable yet, do not worry. You will be seeing them quite a bit in future chapters. Make this mistake by force-unwrapping an optional when it is nil.

Next, examine the error and understand what the error is telling you. Swift provides functions to help developers transform data into something meaningful for the user or accomplish some other task. These chapters also describe how to use the system functions provided by the Swift language as well as how to create your own functions to accomplish your goals.

It is often necessary to be able to keep those values together and pass them around your code. Collections make these operations convenient. Swift has a number of collection types. The first we will cover is called an Array. Arrays are an ordered collection of values. Each position in an array is identified by an index, and any value can appear multiple times in an array.

Arrays are typically used when the order of the values is important or useful to know, but it is not a prerequisite that the order of the values be meaningful. To get started, create a new Swift playground called Arrays.

Create Arrays. Listing 9. Much of that syntax should look familiar. For example, the var keyword means that bucketList is a variable. This means that bucketList is mutable, so the array can be changed.

There are also immutable arrays, which we will discuss later in this chapter. This code tells bucketList what sort of instances it can accept. Here, your array will accept instances of the String type. Arrays can hold instances of any type.

Because this array will hold information concerning your future goals, it makes sense that it takes instances of String. There is an alternative syntax for declaring an array. Make the following change in your playground. Your bucketList is only declared. It is not yet initialized.

This means that it is not yet ready to accept instances of the String type. If you were to try to append an item to your bucketList, you would get an error saying that you are trying to add something before your bucketList is initialized. Change your declaration of bucketList to initialize the array in the same line. An Array literal is a shorthand syntax that initializes an array with whatever instances you include.

In this case, you initialize bucketList with the bucket item to climb Mt. Remove the type declaration from your code to use type inference. Your bucket list still contains the same item, and it still will only accept instances of the String type. The only difference is that it now infers this based on the type of the instance used to initialize it. If you were to try to add an integer to this array, you would see an error telling you that you cannot add an instance of Int to your array because it is expecting instances of the String type.

Sadly, you do not have all that many ambitions in there yet. Update your list with another ambition. Your playground should look like Figure 9. Figure 9.

But what if you have a change of heart? Or — thinking positively — what happens when you accomplish one of the items on your list? Suppose last weekend you settled in and spent 10 hours watching the Lord of the Rings series. Now it is time to take that item off your list. This is called the quick look Figure 9. The count of items in your array is now 5. The item formerly at the second index — your movie marathon — is gone. Why is the item at the second index not the hot air balloon voyage?

Arrays are zero- indexed, so bucketList[0] is equal to "Climb Mt. You are at a party, and the topic of bucket lists comes up. No problem! It is easy to find the number of items in an array.

Arrays keep track of the number of items in them via the count property. Use it to print the number of bucket list items you have to the console. You can easily do this using subscripting, which allows you to access specific indices in your array.

Notice that your first three items print to the console. You can also use the same basic syntax to log a single item, such as print bucketList[2]. Subscripting is a powerful feature. After all, you do not want to go on a walkabout just anywhere. Only a walkabout in Australia will do. You can use subscripting to change an item at a particular index or range of indices. This assignment works because the instance at index 2 is of the same type as the instance you added to it — "Go on a walkabout" and " in Australia" are both of the String type.

Thus, you change the value at index 2 to be: "Go on a walkabout in Australia". Thinking about all of these adventures has gotten you excited, and now you are having trouble sleeping. Since reading usually helps, you start to read up on climbing Mt. You discover that it is pretty dangerous, so you decide to update your top bucket item with a slightly less ambitious goal.

That is better. Now your top bucket list item is safer, but still quite adventurous. While you are now happy with the content of your bucket list, you might not be all that happy that you had to type bucketList. What if I made an array of all the bucket list items I want to add? I would only have to type bucketList. Next, you make a for-in loop that iterates through each item in the array and appends it to your bucketList.

You use the item variable in the local scope of the loop to append it to your bucket list array. You are about to fall asleep, happy in how you have refactored your code to make it more concise and keep it just as expressive — but then a bolt of inspiration strikes. Maybe I can use the addition and assignment operator! Finally, suppose you decide on a new goal — tobogganing across Alaska — that is more important than going on walkabout in Australia but less important than flying a hot air balloon to Fiji.

The first argument takes the instance to add to the array. Recall that your array takes String instances. The second argument takes the index for where you would like to add the new element in the array. With your list fully formed, you lay your head down and dream of flying hot air balloons to mountain islands. There, you meet a friend, named Myron, who had been at the party with you. Myron was inspired by your bucketList and decided to make his own bucket list modeled after yours.

He went home after the party and wrote out all of your items, and now he wants to make sure that he got everything correct. She could still see the sensuality, the earthiness, the familiar readiness. And her own body was mirroring all of those responses. She turned away, finished the glass of water, and set the glass on the counter.

Her entire body was alive, tingling. More than water in the desert, more than fire in winter. Home Forum Login. Download PDF Download. All rights reserved. Printed in the United States of America. They can be reached at or corpsales pearsoned. Today is the day you stop thinking about being a programmer and start becoming one.

Check out our schedule and get started today. Our Books. Need help working through one of our books? Visit our Book Forums. Kotlin Programming: The Big Nerd Ranch Guide Book 2nd Edition This updated guide will walk you through writing your first line of Kotlin code and will guide you through many newer features that developers have been craving, like Coroutines and Multiplatform support.

Read More. Front-End Web Development: The Big Nerd Ranch Guide Discover how to build a solid foundation for creating rich web experiences across platforms and work through step-by-step examples. Speak with a nerd. Alexander L. Our clients. When it comes to iOS and Android, where should I start?

I need help with the exercises in my book. Can I get early access to or a pre-release of a book? I own the print version of a Big Nerd Ranch book.



0コメント

  • 1000 / 1000