ebook img

The Swift Programming Language - SwiftBook PDF

431 Pages·2014·4.16 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview The Swift Programming Language - SwiftBook

The Swift Programming Language Contents Welcome to Swift 14 About Swift 15 A Swift Tour 16 Simple Values 16 Control Flow 18 Functions and Closures 21 Objects and Classes 24 Enumerations and Structures 29 Protocols and Extensions 32 Generics 34 Language Guide 36 The Basics 37 Constants and Variables 37 Declaring Constants and Variables 38 Type Annotations 38 Naming Constants and Variables 39 Printing Constants and Variables 40 Comments 41 Semicolons 41 Integers 42 Integer Bounds 42 Int 42 UInt 43 Floating-Point Numbers 43 Type Safety and Type Inference 43 Numeric Literals 45 Numeric Type Conversion 46 Integer Conversion 46 Integer and Floating-Point Conversion 47 Type Aliases 48 2014-05-30 | Copyright © 2014 Apple Inc. All Rights Reserved. Apple Confidential Information. 2 Booleans 48 Tuples 50 Optionals 51 If Statements and Forced Unwrapping 52 Optional Binding 53 nil 54 Implicitly Unwrapped Optionals 54 Assertions 56 Debugging with Assertions 56 When to Use Assertions 57 Basic Operators 58 Terminology 58 Assignment Operator 59 Arithmetic Operators 59 Remainder Operator 60 Floating-Point Remainder Calculations 61 Increment and Decrement Operators 62 Unary Minus Operator 63 Unary Plus Operator 63 Compound Assignment Operators 63 Comparison Operators 64 Ternary Conditional Operator 65 Range Operators 66 Closed Range Operator 66 Half-Closed Range Operator 66 Logical Operators 67 Logical NOT Operator 67 Logical AND Operator 68 Logical OR Operator 68 Combining Logical Operators 69 Explicit Parentheses 69 Strings and Characters 71 String Literals 71 Initializing an Empty String 72 String Mutability 73 Strings Are Value Types 73 Working with Characters 74 Counting Characters 74 2014-05-30 | Copyright © 2014 Apple Inc. All Rights Reserved. Apple Confidential Information. 3 Contents Concatenating Strings and Characters 75 String Interpolation 76 Comparing Strings 76 String Equality 77 Prefix and Suffix Equality 77 Uppercase and Lowercase Strings 78 Unicode 79 Unicode Terminology 79 Unicode Representations of Strings 79 Collection Types 82 Arrays 82 Array Type Shorthand Syntax 82 Array Literals 83 Accessing and Modifying an Array 83 Iterating Over an Array 86 Creating and Initializing an Array 87 Dictionaries 88 Dictionary Literals 88 Accessing and Modifying a Dictionary 90 Iterating Over a Dictionary 91 Creating an Empty Dictionary 93 Mutability of Collections 93 Control Flow 95 For Loops 95 For-In 95 For-Condition-Increment 98 While Loops 99 While 100 Do-While 102 Conditional Statements 103 If 104 Switch 105 Control Transfer Statements 112 Continue 113 Break 113 Fallthrough 115 Labeled Statements 116 2014-05-30 | Copyright © 2014 Apple Inc. All Rights Reserved. Apple Confidential Information. 4 Contents Functions 120 Defining and Calling Functions 120 Function Parameters and Return Values 121 Multiple Input Parameters 122 Functions Without Parameters 122 Functions Without Return Values 122 Functions with Multiple Return Values 123 Function Parameter Names 124 External Parameter Names 125 Shorthand External Parameter Names 126 Default Parameter Values 127 External Names for Parameters with Default Values 128 Variadic Parameters 128 Constant and Variable Parameters 129 In-Out Parameters 130 Function Types 132 Using Function Types 133 Function Types as Parameter Types 133 Function Types as Return Types 134 Nested Functions 135 Closures 137 Closure Expressions 138 The Sort Function 138 Closure Expression Syntax 139 Inferring Type From Context 140 Implicit Returns from Single-Expression Closures 140 Shorthand Argument Names 140 Operator Functions 141 Trailing Closures 141 Capturing Values 144 Closures Are Reference Types 147 Enumerations 148 Enumeration Syntax 148 Matching Enumeration Values with a Switch Statement 150 Associated Values 151 Raw Values 153 Classes and Structures 156 2014-05-30 | Copyright © 2014 Apple Inc. All Rights Reserved. Apple Confidential Information. 5 Contents Comparing Classes and Structures 156 Definition Syntax 157 Class and Structure Instances 158 Accessing Properties 158 Memberwise Initializers for Structure Types 159 Structures and Enumerations Are Value Types 159 Classes Are Reference Types 161 Identity Operators 162 Pointers 163 Choosing Between Classes and Structures 163 Assignment and Copy Behavior for Collection Types 164 Assignment and Copy Behavior for Dictionaries 165 Assignment and Copy Behavior for Arrays 166 Properties 170 Stored Properties 170 Stored Properties of Constant Structure Instances 171 Lazy Stored Properties 171 Stored Properties and Instance Variables 173 Computed Properties 173 Shorthand Setter Declaration 175 Read-Only Computed Properties 176 Property Observers 177 Global and Local Variables 179 Type Properties 179 Type Property Syntax 180 Querying and Setting Type Properties 181 Methods 185 Instance Methods 185 Local and External Parameter Names for Methods 186 Modifying External Parameter Name Behavior for Methods 188 The self Property 188 Modifying Value Types from Within Instance Methods 189 Assigning to self Within a Mutating Method 190 Type Methods 191 Subscripts 195 Subscript Syntax 195 Subscript Usage 196 2014-05-30 | Copyright © 2014 Apple Inc. All Rights Reserved. Apple Confidential Information. 6 Contents Subscript Options 197 Inheritance 200 Defining a Base Class 200 Subclassing 201 Overriding 203 Accessing Superclass Methods, Properties, and Subscripts 204 Overriding Methods 204 Overriding Properties 205 Preventing Overrides 208 Initialization 209 Setting Initial Values for Stored Properties 209 Initializers 209 Default Property Values 210 Customizing Initialization 210 Initialization Parameters 211 Local and External Parameter Names 211 Optional Property Types 213 Modifying Constant Properties During Initialization 213 Default Initializers 214 Memberwise Initializers for Structure Types 215 Initializer Delegation for Value Types 215 Class Inheritance and Initialization 218 Designated Initializers and Convenience Initializers 218 Initializer Chaining 219 Two-Phase Initialization 220 Initializer Inheritance and Overriding 223 Automatic Initializer Inheritance 224 Syntax for Designated and Convenience Initializers 224 Designated and Convenience Initializers in Action 225 Setting a Default Property Value with a Closure or Function 230 Deinitialization 233 How Deinitialization Works 233 Deinitializers in Action 234 Automatic Reference Counting 237 How ARC Works 237 ARC in Action 238 2014-05-30 | Copyright © 2014 Apple Inc. All Rights Reserved. Apple Confidential Information. 7 Contents Strong Reference Cycles Between Class Instances 239 Resolving Strong Reference Cycles Between Class Instances 242 Weak References 243 Unowned References 246 Unowned References and Implicitly Unwrapped Optional Properties 249 Strong Reference Cycles for Closures 250 Resolving Strong Reference Cycles for Closures 254 Defining a Capture List 254 Weak and Unowned References 254 Optional Chaining 257 Optional Chaining as an Alternative to Forced Unwrapping 257 Defining Model Classes for Optional Chaining 259 Calling Properties Through Optional Chaining 261 Calling Methods Through Optional Chaining 262 Calling Subscripts Through Optional Chaining 263 Linking Multiple Levels of Chaining 264 Chaining on Methods With Optional Return Values 265 Type Casting 267 Defining a Class Hierarchy for Type Casting 267 Checking Type 269 Downcasting 269 Type Casting for Any and AnyObject 271 AnyObject 271 Any 272 Nested Types 275 Nested Types in Action 275 Referring to Nested Types 277 Extensions 278 Extension Syntax 278 Computed Properties 279 Initializers 280 Methods 282 Mutating Instance Methods 283 Subscripts 283 Nested Types 284 2014-05-30 | Copyright © 2014 Apple Inc. All Rights Reserved. Apple Confidential Information. 8 Contents Protocols 287 Protocol Syntax 287 Property Requirements 288 Method Requirements 290 Mutating Method Requirements 291 Protocols as Types 293 Delegation 294 Adding Protocol Conformance with an Extension 298 Declaring Protocol Adoption with an Extension 299 Collections of Protocol Types 300 Protocol Inheritance 301 Protocol Composition 302 Checking for Protocol Conformance 303 Optional Protocol Requirements 306 Generics 310 The Problem That Generics Solve 310 Generic Functions 311 Type Parameters 313 Naming Type Parameters 313 Generic Types 314 Type Constraints 317 Type Constraint Syntax 318 Type Constraints in Action 318 Associated Types 320 Associated Types in Action 320 Extending an Existing Type to Specify an Associated Type 323 Where Clauses 323 Advanced Operators 327 Bitwise Operators 327 Bitwise NOT Operator 328 Bitwise AND Operator 328 Bitwise OR Operator 329 Bitwise XOR Operator 330 Bitwise Left and Right Shift Operators 330 Overflow Operators 334 Value Overflow 334 Value Underflow 335 Division by Zero 336 2014-05-30 | Copyright © 2014 Apple Inc. All Rights Reserved. Apple Confidential Information. 9 Contents Precedence and Associativity 337 Operator Functions 338 Prefix and Postfix Operators 339 Compound Assignment Operators 340 Equivalence Operators 341 Custom Operators 342 Precedence and Associativity for Custom Infix Operators 343 Language Reference 345 About the Language Reference 346 How to Read the Grammar 346 Lexical Structure 347 Whitespace and Comments 347 Identifiers 347 Keywords 348 Literals 348 Integer Literals 349 Floating-Point Literals 349 String Literals 350 Operators 351 Types 353 Type Annotation 353 Type Identifier 354 Tuple Type 354 Function Type 355 Array Type 356 Optional Type 357 Implicitly Unwrapped Optional Type 358 Protocol Composition Type 359 Metatype Type 360 Type Inheritance Clause 361 Type Inference 361 Expressions 363 Prefix Expressions 363 Binary Expressions 364 Assignment Operator 366 2014-05-30 | Copyright © 2014 Apple Inc. All Rights Reserved. Apple Confidential Information. 10 Contents Ternary Conditional Operator 367 Type-Casting Operators 367 Primary Expressions 368 Literal Expression 368 Self Expression 369 Superclass Expression 370 Closure Expression 371 Implicit Member Expression 373 Parenthesized Expression 373 Wildcard Expression 373 Postfix Expressions 374 Function Call Expression 374 Initializer Expression 375 Explicit Member Expression 375 Postfix Self Expression 376 Dynamic Type Expression 377 Subscript Expression 377 Forced-Value Expression 378 Optional-Chaining Expression 378 Statements 380 Loop Statements 380 For Statement 380 For-In Statement 381 While Statement 382 Do-While Statement 382 Branch Statements 383 If Statement 383 Switch Statement 384 Labeled Statement 386 Control Transfer Statements 387 Break Statement 387 Continue Statement 387 Fallthrough Statement 388 Return Statement 388 Declarations 390 Module Scope 390 Code Blocks 390 Import Declaration 391 2014-05-30 | Copyright © 2014 Apple Inc. All Rights Reserved. Apple Confidential Information. 11 Contents Constant Declaration 391 Variable Declaration 392 Stored Variables and Stored Variable Properties 393 Computed Variables and Computed Properties 393 Stored Variable Observers and Property Observers 394 Class and Static Variable Properties 395 Type Alias Declaration 395 Function Declaration 396 Parameter Names 397 Special Kinds of Parameters 398 Special Kinds of Methods 398 Curried Functions and Methods 399 Enumeration Declaration 399 Enumerations with Cases of Any Type 400 Enumerations with Raw Cases Values 400 Accessing Enumeration Cases 401 Structure Declaration 402 Class Declaration 403 Protocol Declaration 404 Protocol Property Declaration 405 Protocol Method Declaration 406 Protocol Initializer Declaration 406 Protocol Subscript Declaration 406 Protocol Associated Type Declaration 407 Initializer Declaration 407 Deinitializer Declaration 408 Extension Declaration 409 Subscript Declaration 410 Operator Declaration 411 Attributes 414 Declaration Attributes 414 Declaration Attributes Used by Interface Builder 417 Type Attributes 417 Patterns 418 Wildcard Pattern 418 Identifier Pattern 419 Value-Binding Pattern 419 Tuple Pattern 420 2014-05-30 | Copyright © 2014 Apple Inc. All Rights Reserved. Apple Confidential Information. 12 Contents Enumeration Case Pattern 420 Type-Casting Patterns 421 Expression Pattern 421 Generic Parameters and Arguments 423 Generic Parameter Clause 423 Where Clauses 424 Generic Argument Clause 425 Summary of the Grammar 427 Statements 427 Generic Parameters and Arguments 427 Declarations 427 Patterns 428 Attributes 428 Expressions 429 Lexical Structure 429 Types 430 2014-05-30 | Copyright © 2014 Apple Inc. All Rights Reserved. Apple Confidential Information. 13 Contents Important: This is a preliminary document for an API or technology in development. Apple is supplying this information to help you plan for the adoption of the technologies and programming interfaces described herein for use on Apple-branded products. This information is subject to change, and software implemented according to this document should be tested with final operating system software and final documentation. Newer versions of this document may be provided with future betas of the API or technology. ● About Swift (page 15) ● A Swift Tour (page 16) 2014-05-30 | Copyright © 2014 Apple Inc. All Rights Reserved. Apple Confidential Information. 14 Welcome to Swift Swift is a new programming language for iOS and OS X apps that builds on the best of C and Objective-C, without the constraints of C compatibility. Swift adopts safe programming patterns and adds modern features to make programming easier, more flexible, and more fun. Swift’s clean slate, backed by the mature and much-loved Cocoa and Cocoa Touch frameworks, is an opportunity to reimagine how software development works. Swift has been years in the making. Apple laid the foundation for Swift by advancing our existing compiler, debugger, and framework infrastructure. We simplified memory management with Automatic Reference Counting (ARC). Our framework stack, built on the solid base of Foundation and Cocoa, has been modernized and standardized throughout. Objective-C itself has evolved to support blocks, collection literals, and modules, enabling framework adoption of modern language technologies without disruption. Thanks to this groundwork, we can now introduce a new language for the future of Apple software development. Swift feels familiar to Objective-C developers. It adopts the readability of Objective-C’s named parameters and the power of Objective-C’s dynamic object model. It provides seamless access to existing Cocoa frameworks and mix-and-match interoperability with Objective-C code. Building from this common ground, Swift introduces many new features and unifies the procedural and object-oriented portions of the language. Swift is friendly to new programmers. It is the first industrial-quality systems programming language that is as expressive and enjoyable as a scripting language. It supports playgrounds, an innovative feature that allows programmers to experiment with Swift code and see the results immediately, without the overhead of building and running an app. Swift combines the best in modern language thinking with wisdom from the wider Apple engineering culture. The compiler is optimized for performance, and the language is optimized for development, without compromising on either. It’s designed to scale from “hello, world” to an entire operating system. All this makes Swift a sound future investment for developers and for Apple. Swift is a fantastic way to write iOS and OS X apps, and will continue to evolve with new features and capabilities. Our goals for Swift are ambitious. We can’t wait to see what you create with it. 2014-05-30 | Copyright © 2014 Apple Inc. All Rights Reserved. Apple Confidential Information. 15 About Swift

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.