An Introduction to Swift

An Introduction to Swift

APPENDIX A An Introduction to Swift Until recently, writing an iPhone or iPad application meant working with Objective-C. Because of its unusual syntax, Objective-C is one of the most polarizing of programming languages—people tend to love it or hate it. At the World Wide Developer Conference in 2014, Apple changed all that by unveiling an alternative—a new language called Swift. Swift’s syntax is designed to be easily recognizable to programmers who are used to some of the more popular object-oriented programming languages like C++ and Java, therefore making it easier for them to start writing applications for iOS (and for Macs since Swift is also fully supported as a development language on macOS). This appendix covers the parts of Swift that you’ll need to know in order to understand the example code in this book. I assume that you already have some programming experience and that you know what variables, functions, methods, and classes are. This appendix is neither a reference nor an exhaustive guide to the language—for that, there are numerous other resources, some of which are listed in Chapter 1. Swift Basics One of the most useful new features introduced in Xcode 6 alongside Swift is the playground. As the name suggests, a playground is a place where you can go to play with code without having to create an environment in which to run it—just open a playground, type in some code, and see the results. Playgrounds are a great place to prototype something new, and they are also an ideal place to start learning a new language, so you’re going to use them throughout this appendix. Let’s begin by creating a new playground. Start Xcode and go to File ➤ New ➤ Playground. In the dialog that opens, choose an iOS playground of Blank type (Figure A-1). Then choose a name for your playground (something like SwiftBasics) and make sure that Platform is iOS. Then press Next. Choose the folder in which your playground will be saved and then click Create. Xcode creates the playground and opens it in a new window, as shown in Figure A-2. As you read through the examples in this appendix, feel free to experiment by adding code of your own to the playground or by modifying the examples to see what happens. © Molly K. Maskrey 2017 491 M. K. Maskrey, Beginning iPhone Development with Swift 4, https://doi.org/10.1007/978-1-4842-3072-5 APPENDIX A ■ An InTROdUCTiOn TO SWiFT Figure A-1. Choose a Blank iOS playground Figure A-2. The newly created playground 492 APPENDIX A ■ An InTROdUCTiOn TO SWiFT Playgrounds, Comments, Variables, and Constants Let’s take a moment to look at what you’ve got in your playground. It’s divided into two areas—code is on the left, and results appear on the right. As you type code, the Swift compiler compiles and executes it and shows you the result almost immediately. The code in Figure A-1 declares a new variable called str and initializes it with the string "Hello, playground". You can see this string in the results column on the right. Try changing the value and notice that the result updates to match as soon as you stop typing. The code on line 1 in Figure A-1 is a comment. Anything following the character sequence // up to the end of the line is ignored by the compiler. Here, the comment occupies the whole line, but that’s not the only option. You could add a comment to the end of a line of code too: var str = "Hello, playground" // my comment for this line To write a comment that’s longer than one line, start it with /* and end it with */, like this: /* This is a comment that occupies More than one line. */ There are various different ways to write a multiline comment. Some people like to make it clear that a line is part of a comment by starting each line with a * character. /* * This is a comment that occupies * More than one line. */ Other people like to write single-line comments like this: /* This is another way to write a single-line comment. */ The import statement on line 3 of Figure A-1 makes Apple’s UIKit framework available for use in the playground. import UIKit IOS includes many frameworks, some of which you’ll read about in this book. UIKit is the user interface framework, which you’ll be using in all of your code examples. Another framework that you’ll frequently make use of is Foundation, which contains classes that provide basic functionality like date and time handling, collections, file management, networking, and much more. To get access to this framework, you need to import it, like this: import Foundation However, UIKit automatically imports Foundation, so any playground that imports UIKit gets access to Foundation for free, without having to add an explicit import for it. Line 5 is the first (and only) line of executable code in this playground. var str = "Hello, playground" 493 APPENDIX A ■ An InTROdUCTiOn TO SWiFT The var keyword declares a new variable with a given name. Here, the variable is called str, which is appropriate because it’s a string. Swift is very liberal with variable names: you can use almost any character you like in the name, with the exception of the first character, which is somewhat restricted. You can find the precise rules in Apple’s documentation at https://developer.apple.com/library/ios/documentation/ Swift/Conceptual/Swift_Programming_Language. Following the declaration of the variable comes an expression that assigns its initial value. You don’t have to initialize a variable when you declare it, but you must do so before you use it (i.e., before you execute any code that reads its value). However, if you choose to assign a value, then Swift can infer the variable’s type, saving you the trouble of stating it explicitly. In this example, Swift infers that str is a string variable because it was initialized with a string literal. If you choose not to provide an initializer (perhaps because there is no fixed initial value), you must declare the variable’s type by appending it to the name and separated from it by a colon, like this: var str2: String // an uninitialized variable Try changing the code on line 5 of the playground to this: var str: String str = "Hello, playground" This is completely equivalent to the original code, but now you’ve had to explicitly state that str is a string variable (String is the Swift type that represents a string). In most cases, it’s easier to combine the declaration and initialization and allow the compiler to infer the variable’s type. Here’s another example that makes use of Swift’s type inference feature: var count = 2 Here, the compiler infers that the count variable is an integer. Its actual type is Int (you’ll cover the numeric types that Swift provides in the next section). How can you be sure that this is the case? Easy. Let Swift tell you. Type the preceding code into the playground, hover the mouse over count, and hold down the ⌥ (Option) key. The cursor changes to a question mark. Now click the mouse and Swift shows you the type that it’s inferred for the variable in a pop-up, as shown in Figure A-3. Figure A-3. Getting the inferred type of a variable The fact that you haven’t explicitly declared the type of a variable doesn’t mean that it doesn’t have one or that you can play fast and loose with it. Swift assigns a type when the variable is declared, and then you have to stick with that type. Unlike dynamic languages like JavaScript, you can’t change the type of a variable simply by assigning a new value to it. Try doing this: var count = 2 count = "Two" 494 APPENDIX A ■ An InTROdUCTiOn TO SWiFT Attempting to assign a string value to an integer variable is an error; you’ll see a red marker in the margin on the left of the playground. Click it, and Swift displays a message explaining the problem (see Figure A-4). Figure A-4. Swift is not a dynamic language. You can’t change the type of a variable. If you’ve programmed before, you may notice that you aren’t bothering to add semicolons at the end of your statements. That’s one of the many nice little features of Swift: it’s almost never necessary to end a statement with a semicolon. If you’re used to writing in C, C++, Objective-C, or Java, that will probably feel a bit strange at first, but after a while, you’ll get used to it. Of course, you can type the semicolon if you want, but most likely you’ll wind up not doing so. The only time you must use a semicolon is if you want to write two statements on the same line. This code is not valid: var count = 2 count = 3 Add a semicolon, and the compiler is happy again. var count = 2; count = 3 As the preceding line of code shows, you can change the value of a variable. That’s why it’s called a variable, after all. What if you just want to give a name to a fixed value? In other words, you want to create a constant and give it a name. For that, Swift provides the let statement, which is just like var, except that you must provide an initial value.

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    62 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us