logo资料库

Learn.Swift.on.the.Mac.For.OS.X.and.iOS.1484203771.pdf

第1页 / 共254页
第2页 / 共254页
第3页 / 共254页
第4页 / 共254页
第5页 / 共254页
第6页 / 共254页
第7页 / 共254页
第8页 / 共254页
资料共254页,剩余部分请下载后查看
Contents at a Glance
Contents
About the Author
About the Technical Reviewer
Acknowledgments
Introduction
Chapter 1: Hello Swift
Improvements over Objective-C
Type Inference
Type Safety
Control Flow
Optionals
Strings
Unicode
Other Improvements
Requirements
Getting Xcode
Quick Tour of Xcode
Quick Tour of Swift
Basic Types
Aggregate Types
Control Flow
Functions
Objects
Generics
Getting the Sample Code
Summary
Chapter 2: The Swift Playground in Xcode 6
Getting Started with a Playgorund
Custom QuickLook Plugins
XCShowView
XCCaptureValue
XCPSetExecutionShouldContinueIndefinitely
Custom Modules for Playground
Importing Your Code
Summary
Chapter 3: Accessing Swift’s Compiler and Interpreter: REPL
What is REPL?
LLDB and the Swift REPL
Summary
Chapter 4: Introduction to Object-Oriented Programming
The Concept Behind OOP
Indirection and Variables
Procedural Programming
Objected Oriented Implementation
Summary
Chapter 5: Constants, Variables, and Data Types
Type Annotation
Identifiers
Console Output
Integers
Floating-Point Numbers
Numeric Literals
Conversion
Booleans
Characters
Strings
Collection Types
Arrays
Dictionaries
Tuples
Optionals
Summary
Chapter 6: Operators
Syntax
Notation
Precedence
Associativity
Swift Operators
Prefix
Infix
Bitwise Shift (precedence 160)
Multiplicative (associativity left, precedence 150)
Additive (associativity, left precedence 140)
Range (precedence 135)
Cast (precedence 132)
Comparative (precedence 130)
Conjunctive (associativity, left precedence 120)
Disjunctive (associativity, left precedence 110)
Nil Coalescing (associativity, right precedence 110)
Ternary Conditional (associativity, right precedence 100)
Assignment (associativity, right precedence 90)
Postfix
Overloading Operators
Unary Operator
Binary Operators
Summary
Chapter 7: Flow Control
For Loops
For-in
For-conditional-Increment
While
Do-while
Branch Statements
Switch
Range Matching
Tuples
Value Binding
String Matching
Where Clause
Control Transfer Statements
Continue
Break
Fallthrough
Return
Labeled Statements
Summary
Chapter 8: Functions and Closures
Defining Functions
Calling a Function
Parameter Names
Default Values
Variadic Parameters
Mutablity of Parameters
In-Out Parameters
Function Types
Functions as Parameters
Functions as Return Values
Nested Functions
Closures
Closure Syntax
Inferring Types from Context
Implicit Returns
Shorthand Argument Names
Trailing Closures
Capturing Values
Summary
Chapter 9: Classes and Structures
Commonality
Definition
Accessing Properties
Value Types vs. Reference Types
Choosing Between Classes or Structures
Properties
Stored Properties
Lazy Stored Properties
Computed Properties
Property Observers
Type Properties
Summary
Chapter 10: Methods
Instance Methods
Modifying Type State
Type Methods
Summary
Chapter 11: Access Control
Modules and Source Files
Access Levels
Syntax
Classes
Subclassing
Class Members
Functions
Enumerations
Nested Types
Getters and Setters
Initializers
Protocols
Extensions
Typealias
Summary
Chapter 12: Inheritance
Terminology
Defining a Base Class
Subclassing
Properties
Preventing Overriding
Summary
Chapter 13: Extensions
Creating an Extension
Computed Properties
Initializers
Methods
Mutating Methods
Subscripts
Nested Types
Summary
Chapter 14: Memory Management and ARC
Object Life Cycle
Reference Counting
Object Ownership
ARC
Strong Reference Cycles
Resolving Strong Reference Cycles
Weak References
Unowned Reference
Strong Reference Cycles and Closures
Summary
Chapter 15: Protocols
Syntax
Properties
Methods
Initializers
Protocols as Types
Delegation
Conformance with Extensions
Protocols and Collection Types
Protocol Inheritance
Protocol Composition
Summary
Chapter 16: Generics
Generic Functions
Generic Types
Associated Types
Summary
Chapter 17: Expressions
Primary Expressions
Prefix Expressions
Postfix Expressions
Binary Expressions
Assignment Operator
Ternary Conditional
Casting Operators
Self and Super
Closures and Functions
Closures
Function Calls
Implicit Member Expression
Optionals
Summary
Chapter 18: Interoperability with Objective-C
Import Process
Interoperability
Object Initialization
Failable Initializers
Properties
Methods
Blocks
Object Comparison
Type Compatibility
Dynamic Dispatch
Selectors
Property Attributes
Namespaces and Class
Cocoa Data Types
Foundation Functions
Core Foundation
Interacting with C
Summary
Chapter 19: Mix and Match
Importing Objective-C into Swift in the Same App Target
Importing Swift into Objective-C in the Same App Target
Importing Objective-C into Swift in the Same Framework Target
Importing Swift into Objective-C in the Same Framework Target
Importing Frameworks
Using Swift in Objective-C
Summary
Chapter 20: Working with Core Data
NSManagedObjectContext
NSManagedObject
NSManagedObjectModel
NSPersistentStoreCoordinator
NSFetchRequest
NSPredicate
Creating An Application
Defining Data Objects
Adding an Object Editor
Showing the Editor
Entity Classes
Summary
Chapter 21: Consuming RESTful Services
HTTP Methods
Being Stateless
Endpoints
Data Formats
Network Access
Summary
Chapter 22: Developing a Swift-Based Application
The Project
Creating a Project
Creating A Sample
Detail View
Summary
Index
For your convenience Apress has placed some of the front matter material after the index. Please use the Bookmarks and Contents at a Glance links to access them.
Contents at a Glance About the Author ���������������������������������������������������������������������������������������������������xvii About the Technical Reviewer ��������������������������������������������������������������������������������xix Acknowledgments ��������������������������������������������������������������������������������������������������xxi Introduction ����������������������������������������������������������������������������������������������������������xxiii ■ Chapter 1: Hello Swift �������������������������������������������������������������������������������������������� 1 ■ Chapter 2: The Swift Playground in Xcode 6 ������������������������������������������������������� 15 ■ Chapter 3: Accessing Swift’s Compiler and Interpreter: REPL ���������������������������� 29 ■ Chapter 4: Introduction to Object-Oriented Programming ���������������������������������� 33 ■ Chapter 5: Constants, Variables, and Data Types ������������������������������������������������ 43 ■ Chapter 6: Operators ������������������������������������������������������������������������������������������� 55 ■ Chapter 7: Flow Control ��������������������������������������������������������������������������������������� 67 ■ Chapter 8: Functions and Closures ���������������������������������������������������������������������� 81 ■ Chapter 9: Classes and Structures ���������������������������������������������������������������������� 93 ■ Chapter 10: Methods ����������������������������������������������������������������������������������������� 103 ■ Chapter 11: Access Control ������������������������������������������������������������������������������� 109 ■ Chapter 12: Inheritance ������������������������������������������������������������������������������������� 117 v
Contents at a Glance vi ■ Chapter 13: Extensions �������������������������������������������������������������������������������������� 123 ■ Chapter 14: Memory Management and ARC ������������������������������������������������������ 129 ■ Chapter 15: Protocols ���������������������������������������������������������������������������������������� 141 ■ Chapter 16: Generics ����������������������������������������������������������������������������������������� 149 ■ Chapter 17: Expressions ������������������������������������������������������������������������������������ 157 ■ Chapter 18: Interoperability with Objective-C ��������������������������������������������������� 165 ■ Chapter 19: Mix and Match ������������������������������������������������������������������������������� 177 ■ Chapter 20: Working with Core Data ����������������������������������������������������������������� 185 ■ Chapter 21: Consuming RESTful Services ��������������������������������������������������������� 203 ■ Chapter 22: Developing a Swift-Based Application ������������������������������������������� 211 Index ��������������������������������������������������������������������������������������������������������������������� 237
Introduction Whenever developers come to a new platform, they are faced with the task of getting to know unfamiliar development tools, design patterns, the standard frameworks available in the new environment, and perhaps even a new programming language. Most of the time, this is all done while trying to deliver an application as soon as possible. In such situations, developers tend to fall back on the patterns and approaches they are familiar with from previous environments, which too often results in code that doesn’t fit the new environment, or in duplicate code that might already be provided by the built-in frameworks. This can cause problems down the road or delays in delivery. It would be great to have colleagues already familiar with the platform who could offer guidance to get you going in the right direction. Well, it’s not always possible to have mentors to help you, and that’s where this books steps in—to be your mentor. The author of this book is a veteran of Apple’s Developer Technical Services organization, and has answered countless questions from software engineers who are new to Apple technology. That experience results in a book that anticipates the most common misunderstandings and takes care to explain not only the how, but also the why of Apple’s development platform. For example, the conceptual basis provided in Chapter 4, “Introduction to Object-Oriented Programming,” gives you the means to place the material that follows into a coherent picture, instead of just tossing you into a flurry of unfamiliar classes, methods, and techniques and hoping you’ll somehow sort it all out with practice. Learn Swift on the Mac provides a step-by-step guide that will help you acquire the skills you need to develop applications for iOS and OS X. xxiii
Hello Swift Chapter 1 Swift is a new language designed by Apple for developing iOS and OS X applications. It takes the best parts of C and Objective-C and adapts them with modern features and patterns. Swift-compiled programs will run on iOS7 or newer and OS X 10.9 (Mavericks) or newer. The two main goals for the language are compatibility with the Cocoa and Cocoa Touch frameworks, and safety, as you’ll see in the upcoming chapters. If you’ve been using Objecive-C, especially the modern syntax, Swift will feel familiar. But Swift’s syntax is actually a major departure from Objective-C. It takes lots of cues from programming languages like Haskell, C#, Ruby, and Python. Some of the technologies I’ll cover in this book are:  Automatic reference counting  Closures (blocks)  Collection literals  Modules  Frameworks  Objective-C runtime  Generics  Operator overloading  Tuples  Namespaces 1
CHAPTER 1: Hello Swift 2 Improvements over Objective-C Let’s take a quick look atsome of the features that make Swift better than Objective-C. I’ll cover these in detail in later chapters. Type Inference In Swift, there is usually no need to specify the type of variables (though you can always specify them); the types of the variables can be inferred by the value being set. Type Safety Conversion between types is done explicitly. The compiler knows more about types in method calls and can use table look-up for methods for dispatch instead of the dynamic dispatch that Objective-C uses. Static dispatch via table look-up enables more checks at compile time, even in the playground. As soon as you enter an expression in the playground, the compiler evaluates it and lets you know of any possible issues with the statement; you can’t run your program until you fix those issues. Here are some features that enhance safety:  Variables and constants are always initialized  Array bounds are always checked.  Raw C pointers are not readly available.  Assignments do not return values.  Overflows are trapped as runtime errors. Control Flow The switch statement has undergone a major overhaul. Now it can select based not only integers, but also on strings, floats, ranges of items, expressions, enums, and so forth. Moreover, there’s no implicit fall-through between case statements. Optionals Variables can now have optional values. What does that mean? It means a variable will either be nil or it will have a valid value. The nil value is distinct from any valid value. Optionals can also be chained together to protect against errors and exceptions. Strings Strings in Swift are much easier to work with, with a clear, simple syntax. You can concatenate strings using the += operator. The mutability of the strings is defined by the language, not the String object. You declare a string as either mutable or nonmutable with the same String object, by using either the let or var keywords.
CHAPTER 1: Hello Swift 3 Unicode Unicode is supported at the core: You can define variables names and function names using full Unicode. The String and Character types are also fully Unicode-compliant and support various encodings, such as UTF-8, UTF-16, and 21-bit Unicode scalers. Other Improvements  Header files are no longer required.  Functions are full-fledged objects; they can be passed as arguments and returned from other fuctions. Functions can be scoped similarly to instance variables.  Comments can be nested.  There are separate operators for assignment (=) and comparison (==), and there’s even an identity operator (===) for checking whether two data elements refer to same object.  There is no defined entry point for programs such as main. If all this sounds good to you (it does to me), let’s go get the tools to start playing with Swift. Requirements Before you can begin playing with Swift, you need to download and install Xcode, the IDE that’s used to build applications for iOS and OS X. You’ll need Xcode 6.1 or later. It’s really easy to download and install Xcode. Here are the basic requirements:  Intel-based Macintosh computer  OS X 10.10 Yosemite (or later)  Free disk space  An Internet connection  An iOS device running iOS 7 (or later) Note As a rule, the later the version of the OS, the better. The examples in the book are developed using Xcode 6.1 running on OS X 10.10 Yosemite and for iOS 8 running on iPhone 5S. Getting Xcode Launch the App Store application and use the search bar on the top right to search for Xcode. . You can then get more information by selecting Xcode, as shown in Figure 1-1, or install it by selecting the Install button.
分享到:
收藏