├── .git-blame-ignore-revs ├── .git-order-file ├── .gitattributes ├── .github ├── ISSUE_TEMPLATE │ ├── BUG_REPORT.yml │ ├── FEATURE_REQUEST.yml │ └── config.yml └── PULL_REQUEST_TEMPLATE.md ├── .gitignore ├── CONTRIBUTING.md ├── LICENSE.txt ├── README.md ├── Style.md ├── TSPL.docc ├── Assets │ ├── CollectionTypes_intro@2x.png │ ├── CollectionTypes_intro~dark@2x.png │ ├── UTF16@2x.png │ ├── UTF16~dark@2x.png │ ├── UTF8@2x.png │ ├── UTF8~dark@2x.png │ ├── UnicodeScalar@2x.png │ ├── UnicodeScalar~dark@2x.png │ ├── barcode_QR@2x.png │ ├── barcode_QR~dark@2x.png │ ├── barcode_UPC@2x.png │ ├── barcode_UPC~dark@2x.png │ ├── bitshiftSigned@2x.png │ ├── bitshiftSignedAddition@2x.png │ ├── bitshiftSignedAddition~dark@2x.png │ ├── bitshiftSignedFour@2x.png │ ├── bitshiftSignedFour~dark@2x.png │ ├── bitshiftSignedMinusFour@2x.png │ ├── bitshiftSignedMinusFourValue@2x.png │ ├── bitshiftSignedMinusFourValue~dark@2x.png │ ├── bitshiftSignedMinusFour~dark@2x.png │ ├── bitshiftSigned~dark@2x.png │ ├── bitshiftUnsigned@2x.png │ ├── bitshiftUnsigned~dark@2x.png │ ├── bitwiseAND@2x.png │ ├── bitwiseAND~dark@2x.png │ ├── bitwiseNOT@2x.png │ ├── bitwiseNOT~dark@2x.png │ ├── bitwiseOR@2x.png │ ├── bitwiseOR~dark@2x.png │ ├── bitwiseXOR@2x.png │ ├── bitwiseXOR~dark@2x.png │ ├── chessBoard@2x.png │ ├── chessBoard~dark@2x.png │ ├── closureReferenceCycle01@2x.png │ ├── closureReferenceCycle01~dark@2x.png │ ├── closureReferenceCycle02@2x.png │ ├── closureReferenceCycle02~dark@2x.png │ ├── computedProperties@2x.png │ ├── computedProperties~dark@2x.png │ ├── coordinateGraphComplex@2x.png │ ├── coordinateGraphComplex~dark@2x.png │ ├── coordinateGraphMedium@2x.png │ ├── coordinateGraphMedium~dark@2x.png │ ├── coordinateGraphSimple@2x.png │ ├── coordinateGraphSimple~dark@2x.png │ ├── cover_opensource.jpg │ ├── initializerDelegation01@2x.png │ ├── initializerDelegation01~dark@2x.png │ ├── initializerDelegation02@2x.png │ ├── initializerDelegation02~dark@2x.png │ ├── initializersExample01@2x.png │ ├── initializersExample01~dark@2x.png │ ├── initializersExample02@2x.png │ ├── initializersExample02~dark@2x.png │ ├── initializersExample03@2x.png │ ├── initializersExample03~dark@2x.png │ ├── macro-ast-input@2x.png │ ├── macro-ast-input~dark@2x.png │ ├── macro-ast-original@2x.png │ ├── macro-ast-original~dark@2x.png │ ├── macro-ast-output@2x.png │ ├── macro-ast-output~dark@2x.png │ ├── macro-ast-result@2x.png │ ├── macro-ast-result~dark@2x.png │ ├── macro-expansion-full@2x.png │ ├── macro-expansion-full~dark@2x.png │ ├── macro-expansion@2x.png │ ├── macro-expansion~dark@2x.png │ ├── memory_increment@2x.png │ ├── memory_increment~dark@2x.png │ ├── memory_map@2x.png │ ├── memory_mapInPlace@2x.png │ ├── memory_mapInPlace~dark@2x.png │ ├── memory_map~dark@2x.png │ ├── memory_share_health_maria@2x.png │ ├── memory_share_health_maria~dark@2x.png │ ├── memory_share_health_oscar@2x.png │ ├── memory_share_health_oscar~dark@2x.png │ ├── memory_shopping@2x.png │ ├── memory_shopping~dark@2x.png │ ├── multilineStringWhitespace@2x.png │ ├── multilineStringWhitespace~dark@2x.png │ ├── overflowAddition@2x.png │ ├── overflowAddition~dark@2x.png │ ├── overflowSignedSubtraction@2x.png │ ├── overflowSignedSubtraction~dark@2x.png │ ├── overflowUnsignedSubtraction@2x.png │ ├── overflowUnsignedSubtraction~dark@2x.png │ ├── referenceCycle01@2x.png │ ├── referenceCycle01~dark@2x.png │ ├── referenceCycle02@2x.png │ ├── referenceCycle02~dark@2x.png │ ├── referenceCycle03@2x.png │ ├── referenceCycle03~dark@2x.png │ ├── remainderInteger@2x.png │ ├── remainderInteger~dark@2x.png │ ├── setEulerDiagram@2x.png │ ├── setEulerDiagram~dark@2x.png │ ├── setVennDiagram@2x.png │ ├── setVennDiagram~dark@2x.png │ ├── sharedStateClass@2x.png │ ├── sharedStateClass~dark@2x.png │ ├── sharedStateStruct@2x.png │ ├── sharedStateStruct~dark@2x.png │ ├── snakesAndLadders@2x.png │ ├── snakesAndLadders~dark@2x.png │ ├── stackPoppedOneString@2x.png │ ├── stackPoppedOneString~dark@2x.png │ ├── stackPushPop@2x.png │ ├── stackPushPop~dark@2x.png │ ├── stackPushedFourStrings@2x.png │ ├── stackPushedFourStrings~dark@2x.png │ ├── staticPropertiesVUMeter@2x.png │ ├── staticPropertiesVUMeter~dark@2x.png │ ├── stringSubstring@2x.png │ ├── stringSubstring~dark@2x.png │ ├── subscriptMatrix01@2x.png │ ├── subscriptMatrix01~dark@2x.png │ ├── subscriptMatrix02@2x.png │ ├── subscriptMatrix02~dark@2x.png │ ├── twoPhaseInitialization01@2x.png │ ├── twoPhaseInitialization01~dark@2x.png │ ├── twoPhaseInitialization02@2x.png │ ├── twoPhaseInitialization02~dark@2x.png │ ├── unownedOptionalReference@2x.png │ ├── unownedOptionalReference~dark@2x.png │ ├── unownedReference01@2x.png │ ├── unownedReference01~dark@2x.png │ ├── unownedReference02@2x.png │ ├── unownedReference02~dark@2x.png │ ├── vectorAddition@2x.png │ ├── vectorAddition~dark@2x.png │ ├── weakReference01@2x.png │ ├── weakReference01~dark@2x.png │ ├── weakReference02@2x.png │ ├── weakReference02~dark@2x.png │ ├── weakReference03@2x.png │ └── weakReference03~dark@2x.png ├── GuidedTour │ ├── AboutSwift.md │ ├── Compatibility.md │ └── GuidedTour.md ├── Info.plist ├── LanguageGuide │ ├── AccessControl.md │ ├── AdvancedOperators.md │ ├── AutomaticReferenceCounting.md │ ├── BasicOperators.md │ ├── ClassesAndStructures.md │ ├── Closures.md │ ├── CollectionTypes.md │ ├── Concurrency.md │ ├── ControlFlow.md │ ├── Deinitialization.md │ ├── Enumerations.md │ ├── ErrorHandling.md │ ├── Extensions.md │ ├── Functions.md │ ├── Generics.md │ ├── Inheritance.md │ ├── Initialization.md │ ├── Macros.md │ ├── MemorySafety.md │ ├── Methods.md │ ├── NestedTypes.md │ ├── OpaqueTypes.md │ ├── OptionalChaining.md │ ├── Properties.md │ ├── Protocols.md │ ├── StringsAndCharacters.md │ ├── Subscripts.md │ ├── TheBasics.md │ └── TypeCasting.md ├── ReferenceManual │ ├── AboutTheLanguageReference.md │ ├── Attributes.md │ ├── Declarations.md │ ├── Expressions.md │ ├── GenericParametersAndArguments.md │ ├── LexicalStructure.md │ ├── Patterns.md │ ├── Statements.md │ ├── SummaryOfTheGrammar.md │ └── Types.md ├── RevisionHistory │ └── RevisionHistory.md ├── The-Swift-Programming-Language.md ├── footer.html ├── header-publish.html └── header-staging.html └── bin ├── find_screenshot_changes ├── preflight ├── publish-book ├── redirects ├── GuidedTour │ ├── Compatibility.html │ └── GuidedTour.html ├── LanguageGuide │ ├── AccessControl.html │ ├── AdvancedOperators.html │ ├── AutomaticReferenceCounting.html │ ├── BasicOperators.html │ ├── ClassesAndStructures.html │ ├── Closures.html │ ├── CollectionTypes.html │ ├── Concurrency.html │ ├── ControlFlow.html │ ├── Deinitialization.html │ ├── Enumerations.html │ ├── ErrorHandling.html │ ├── Extensions.html │ ├── Functions.html │ ├── Generics.html │ ├── Inheritance.html │ ├── Initialization.html │ ├── MemorySafety.html │ ├── Methods.html │ ├── NestedTypes.html │ ├── OpaqueTypes.html │ ├── OptionalChaining.html │ ├── Properties.html │ ├── Protocols.html │ ├── StringsAndCharacters.html │ ├── Subscripts.html │ ├── TheBasics.html │ └── TypeCasting.html ├── ReferenceManual │ ├── AboutTheLanguageReference.html │ ├── Attributes.html │ ├── Declarations.html │ ├── Expressions.html │ ├── GenericParametersAndArguments.html │ ├── LexicalStructure.html │ ├── Patterns.html │ ├── Statements.html │ ├── Types.html │ └── zzSummaryOfTheGrammar.html ├── RevisionHistory │ └── RevisionHistory.html ├── documentation │ └── index.html ├── index.html └── redirect.swift └── update-book-preview /.git-blame-ignore-revs: -------------------------------------------------------------------------------- 1 | # This file is a list of commits that made uninteresting formatting 2 | # changes, which should be ignored by git-blame, so that it can instead 3 | # display more the relevant history and attribution information. 4 | # 5 | # To use this file for a single command, pass it as follows: 6 | # 7 | # git blame --ignore-revs-file .git-blame-ignore-revs 8 | # 9 | # To use this file for all blame operations, run the following command: 10 | # 11 | # git config --local blame.ignoreRevsFile .git-blame-ignore-revs 12 | # 13 | # For more information, see the git-blame(1) man page's discussion of 14 | # the --ignore-revs-file option, and the git-config(1) man page's 15 | # discussion of the blame.ignoreRevsFile option. 16 | 17 | # Convert RST to markdown 18 | 96f0925407c6bd9eadd9d58d253bad3e1ef7a9f2 19 | 20 | # Convert the formal grammar to markdown 21 | 4039ee0ef4e69d2cf6460861f9444a499503db16 22 | 23 | # Clean up formatting of term-definition lists 24 | c914c44ccdbbda757ee43e5d4c777abf24391a1a 25 | -------------------------------------------------------------------------------- /.git-order-file: -------------------------------------------------------------------------------- 1 | # This file lists the chapters of TSPL, in the order they appear in the 2 | # book. When reviewing changes, the diff can be easier to read when it 3 | # appears in this order. 4 | # 5 | # To use this file for single command, run a command like the following: 6 | # 7 | # git log -O .git-order-file 8 | # git diff -O .git-order-file 9 | # 10 | # To use it for all diffs, run the following command: 11 | # 12 | # git config --local diff.orderFile .git-order-file 13 | # 14 | # For more information, see the git-log(1) and git-diff(1) man pages' 15 | # discussions of the -O option, and the git-config(1) man page's 16 | # discussion of diff.orderFile option. 17 | 18 | TSPL.docc/GuidedTour/AboutSwift.md 19 | TSPL.docc/GuidedTour/Compatibility.md 20 | TSPL.docc/GuidedTour/GuidedTour.md 21 | 22 | TSPL.docc/LanguageGuide/TheBasics.md 23 | TSPL.docc/LanguageGuide/BasicOperators.md 24 | TSPL.docc/LanguageGuide/StringsAndCharacters.md 25 | TSPL.docc/LanguageGuide/CollectionTypes.md 26 | TSPL.docc/LanguageGuide/ControlFlow.md 27 | TSPL.docc/LanguageGuide/Functions.md 28 | TSPL.docc/LanguageGuide/Closures.md 29 | TSPL.docc/LanguageGuide/Enumerations.md 30 | TSPL.docc/LanguageGuide/ClassesAndStructures.md 31 | TSPL.docc/LanguageGuide/Properties.md 32 | TSPL.docc/LanguageGuide/Methods.md 33 | TSPL.docc/LanguageGuide/Subscripts.md 34 | TSPL.docc/LanguageGuide/Inheritance.md 35 | TSPL.docc/LanguageGuide/Initialization.md 36 | TSPL.docc/LanguageGuide/Deinitialization.md 37 | TSPL.docc/LanguageGuide/OptionalChaining.md 38 | TSPL.docc/LanguageGuide/ErrorHandling.md 39 | TSPL.docc/LanguageGuide/Concurrency.md 40 | TSPL.docc/LanguageGuide/Macros.md 41 | TSPL.docc/LanguageGuide/TypeCasting.md 42 | TSPL.docc/LanguageGuide/NestedTypes.md 43 | TSPL.docc/LanguageGuide/Extensions.md 44 | TSPL.docc/LanguageGuide/Protocols.md 45 | TSPL.docc/LanguageGuide/Generics.md 46 | TSPL.docc/LanguageGuide/OpaqueTypes.md 47 | TSPL.docc/LanguageGuide/AutomaticReferenceCounting.md 48 | TSPL.docc/LanguageGuide/MemorySafety.md 49 | TSPL.docc/LanguageGuide/AccessControl.md 50 | TSPL.docc/LanguageGuide/AdvancedOperators.md 51 | 52 | TSPL.docc/ReferenceManual/AboutTheLanguageReference.md 53 | TSPL.docc/ReferenceManual/LexicalStructure.md 54 | TSPL.docc/ReferenceManual/Types.md 55 | TSPL.docc/ReferenceManual/Expressions.md 56 | TSPL.docc/ReferenceManual/Statements.md 57 | TSPL.docc/ReferenceManual/Declarations.md 58 | TSPL.docc/ReferenceManual/Attributes.md 59 | TSPL.docc/ReferenceManual/Patterns.md 60 | TSPL.docc/ReferenceManual/GenericParametersAndArguments.md 61 | TSPL.docc/ReferenceManual/SummaryOfTheGrammar.md 62 | 63 | TSPL.docc/RevisionHistory/RevisionHistory.md 64 | 65 | # Files that don't match a pattern listed above, such as assets and 66 | # build scripts, will appear at the end of the diff. 67 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.md linguist-detectable=true 2 | *.md linguist-documentation=false 3 | *.md diff=markdown 4 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/BUG_REPORT.yml: -------------------------------------------------------------------------------- 1 | name: Content Issue 2 | description: Something is missing or incorrect 3 | labels: ["Content Issue"] 4 | body: 5 | - type: markdown 6 | attributes: 7 | value: | 8 | Thank you for contributing to "The Swift Programming Language"! 9 | 10 | Before you submit your issue, please provide the relevant details in the text areas below. 11 | - type: textarea 12 | attributes: 13 | label: Location 14 | description: | 15 | The URL of the content that has a problem. 16 | validations: 17 | required: false 18 | - type: textarea 19 | attributes: 20 | label: Description 21 | description: | 22 | A short description of what's wrong. 23 | validations: 24 | required: true 25 | - type: textarea 26 | attributes: 27 | label: Correction 28 | description: | 29 | What should the documentation say instead? 30 | validations: 31 | required: false 32 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/FEATURE_REQUEST.yml: -------------------------------------------------------------------------------- 1 | name: Enhancement 2 | description: A suggestion for new content 3 | labels: [Enhancement] 4 | body: 5 | - type: markdown 6 | attributes: 7 | value: | 8 | Thank you for contributing to "The Swift Programming Language"! 9 | 10 | Before you submit your issue, please provide the relevant details in the text areas below. 11 | - type: textarea 12 | attributes: 13 | label: Location 14 | description: | 15 | The URL of the chapter or section where the new content would go. 16 | validations: 17 | required: false 18 | - type: textarea 19 | attributes: 20 | label: Description 21 | description: | 22 | A short description of your proposed addition. 23 | validations: 24 | required: true 25 | - type: textarea 26 | attributes: 27 | label: Motivation 28 | description: A description of the use-case this proposed documentation will serve. 29 | validations: 30 | required: false 31 | - type: textarea 32 | attributes: 33 | label: Alternatives Considered 34 | description: If you considered alternative approaches, please include them here. 35 | validations: 36 | required: false 37 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: yes 2 | 3 | contact_links: 4 | - name: Documentation Forums Category 5 | url: https://forums.swift.org/c/92 6 | about: Ask and answer questions about writing documentation 7 | - name: Swift-DocC Forums Category 8 | url: https://forums.swift.org/c/80 9 | about: Ask and answer questions about using Swift-DocC 10 | - name: Swift-DocC Documentation 11 | url: https://www.swift.org/documentation/docc/ 12 | about: Learn about how to use Swift-DocC for authoring documentation 13 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Replace this paragraph with your rationale and a brief summary of what changed. 5 | 6 | 7 | Fixes: https://github.com/apple/swift-book/issues/#### 8 | Fixes: rdar://#### 9 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .docc-build 3 | .swiftpm 4 | /.build 5 | /Package.resolved 6 | /TSPL.docc/header.html 7 | /swift-book 8 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to *The Swift Programming Language* book 2 | 3 | By submitting a pull request, 4 | you represent that you have the right to license your contribution 5 | to Apple and the community, 6 | and agree by submitting the patch 7 | that your contributions are licensed under 8 | the [Swift license](https://swift.org/LICENSE.txt). 9 | 10 | For small changes, 11 | like typo fixes and revisions within a few paragraphs, 12 | the discussion of those changes is usually small enough 13 | to be part of the pull request. 14 | For large changes, 15 | like new chapters and sections, 16 | start a thread in the [Swift forums][forum] 17 | to discuss your approach and identify possible issues 18 | before you invest a lot of time in writing. 19 | In general, 20 | the amount of discussion around a change before making a pull request 21 | corresponds to the size of that change. 22 | 23 | Content in this book follows [Apple Style Guide][asg] 24 | and [this book’s style guide][tspl-style]. 25 | 26 | [asg]: https://help.apple.com/applestyleguide/ 27 | [forum]: https://forums.swift.org/c/swift-documentation/92 28 | [tspl-style]: /Style.md 29 | 30 | ## Working on a feature branch 31 | 32 | If this is your first contribution, 33 | start by making a fork of the Git repository. 34 | 35 | In your fork, 36 | make a new branch starting at `main` 37 | with a brief, descriptive name. 38 | Branch names are ephemeral: 39 | When a pull request is merged, 40 | the merge commit doesn’t include name of your feature branch. 41 | 42 | If you need to incorporate changes from `main` or resolve a merge conflict, 43 | merge `main` into your feature branch. 44 | Before creating a pull request, 45 | you can instead rebase your feature branch onto `main` if you prefer, 46 | but don't rebase commits that are part of a pull request. 47 | 48 | ## Writing commit messages 49 | 50 | Use the Git commit message to communicate with other contributors — 51 | both the people working on the project now 52 | who are reviewing your changes, 53 | and people who join the project in the future 54 | who will need to understand what you changed and why. 55 | 56 | Every commit starts with a one-sentence summary. 57 | The summary usually fits in 50 characters, 58 | but it's ok to exceed that amount occasionally 59 | if rewriting for brevity would make it too hard to read. 60 | If it's hard to write a good summary, 61 | try breaking your changes into multiple smaller commits. 62 | 63 | If you can't explain the commit entirely in its summary, 64 | skip one line and add additional information. 65 | This additional information includes information like 66 | the reasons for the change, 67 | the approach you took when making it, 68 | alternatives you considered, 69 | and a summary of what you changed. 70 | Hard wrap these lines at 72 characters 71 | and leave a blank line between paragraphs. 72 | The body of a commit is plain text, 73 | not markdown like the content of the book. 74 | 75 | Following these formatting conventions in your commit 76 | makes it easier to read 77 | in places like the output from `git` and notification emails. 78 | Most text editors can help you write a commit message 79 | by marking lines that are too long 80 | and hard wrapping text automatically. 81 | 82 | ## Submitting a pull request 83 | 84 | Use the following steps when creating a new pull request: 85 | 86 | 1. Test that your changes build locally by running `docc preview TSPL.docc`. 87 | 2. Create a pull request in this repository. 88 | 3. Write a brief message in the pull request to introduce your work in context. 89 | 90 | Within a few days, 91 | someone will assign reviewers and start a build in CI. 92 | 93 | During the review of the pull request, 94 | add new commits on your branch to incorporate feedback, 95 | but don’t rebase or force push. 96 | Rewriting the branch's history 97 | makes it hard for reviewers to see 98 | what changed since the last time they reviewed your changes. 99 | If there are merge conflicts, 100 | merge `main` into your branch or use the GitHub web UI 101 | to resolve the conflicts when accepting the pull request. 102 | 103 | After a pull request is merged, delete the feature branch. 104 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | 204 | 205 | ## Runtime Library Exception to the Apache 2.0 License: ## 206 | 207 | 208 | As an exception, if you use this Software to compile your source code and 209 | portions of this Software are embedded into the binary product as a result, 210 | you may redistribute such product without providing attribution as would 211 | otherwise be required by Sections 4(a), 4(b) and 4(d) of the License. 212 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # The Swift Programming Language 2 | 3 | This repository contains the source for *The Swift Programming Language* 4 | (sometimes abbreviated as TSPL), 5 | which is published on [docs.swift.org][published] 6 | and built using [Swift-DocC][docc]. 7 | 8 | ## Contributing 9 | 10 | For small changes, 11 | like typo fixes and changes to a few paragraphs, 12 | fork this repository and make a pull request. 13 | 14 | A formal contribution process for this document is still in development. 15 | In the meantime, 16 | start a pitch thread in the [Swift forums][forum] for larger changes 17 | to discuss your approach and identify possible issues 18 | before you invest a lot of time in writing. 19 | 20 | Content in this book follows [Apple Style Guide][asg] 21 | and [this book’s style guide][tspl-style]. 22 | 23 | File bugs about the content using the [issues page][bugs] on Github. 24 | 25 | Discussions and contributions follow the [Swift Code of Conduct][conduct]. 26 | 27 | For more information, see [Contributing to The Swift Programming Language][contributing]. 28 | 29 | [asg]: https://help.apple.com/applestyleguide/ 30 | [bugs]: https://github.com/apple/swift-book/issues 31 | [conduct]: https://www.swift.org/code-of-conduct 32 | [contributing]: /CONTRIBUTING.md 33 | [forum]: https://forums.swift.org/c/swift-documentation/92 34 | [tspl-style]: /Style.md 35 | [published]: https://docs.swift.org/swift-book/documentation/the-swift-programming-language/ 36 | [docc]: https://github.com/apple/swift-docc 37 | 38 | ## Building 39 | 40 | Run `docc preview TSPL.docc` 41 | in this repository's root directory. 42 | 43 | After running DocC, open the link that `docc` outputs 44 | to display a local preview in your browser. 45 | 46 | > Note: 47 | > 48 | > If you installed DocC by downloading a toolchain from Swift.org, 49 | > `docc` is located in `usr/bin/`, 50 | > relative to the installation path of the toolchain. 51 | > Make sure your shell's `PATH` environment variable 52 | > includes that directory. 53 | > 54 | > If you installed DocC by downloading Xcode, 55 | > run `xcrun docc preview TSPL.docc` instead. 56 | 57 | -------------------------------------------------------------------------------- /TSPL.docc/Assets/CollectionTypes_intro@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/CollectionTypes_intro@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/CollectionTypes_intro~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/CollectionTypes_intro~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/UTF16@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/UTF16@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/UTF16~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/UTF16~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/UTF8@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/UTF8@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/UTF8~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/UTF8~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/UnicodeScalar@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/UnicodeScalar@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/UnicodeScalar~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/UnicodeScalar~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/barcode_QR@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/barcode_QR@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/barcode_QR~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/barcode_QR~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/barcode_UPC@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/barcode_UPC@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/barcode_UPC~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/barcode_UPC~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/bitshiftSigned@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/bitshiftSigned@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/bitshiftSignedAddition@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/bitshiftSignedAddition@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/bitshiftSignedAddition~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/bitshiftSignedAddition~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/bitshiftSignedFour@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/bitshiftSignedFour@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/bitshiftSignedFour~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/bitshiftSignedFour~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/bitshiftSignedMinusFour@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/bitshiftSignedMinusFour@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/bitshiftSignedMinusFourValue@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/bitshiftSignedMinusFourValue@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/bitshiftSignedMinusFourValue~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/bitshiftSignedMinusFourValue~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/bitshiftSignedMinusFour~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/bitshiftSignedMinusFour~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/bitshiftSigned~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/bitshiftSigned~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/bitshiftUnsigned@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/bitshiftUnsigned@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/bitshiftUnsigned~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/bitshiftUnsigned~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/bitwiseAND@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/bitwiseAND@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/bitwiseAND~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/bitwiseAND~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/bitwiseNOT@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/bitwiseNOT@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/bitwiseNOT~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/bitwiseNOT~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/bitwiseOR@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/bitwiseOR@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/bitwiseOR~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/bitwiseOR~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/bitwiseXOR@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/bitwiseXOR@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/bitwiseXOR~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/bitwiseXOR~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/chessBoard@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/chessBoard@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/chessBoard~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/chessBoard~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/closureReferenceCycle01@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/closureReferenceCycle01@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/closureReferenceCycle01~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/closureReferenceCycle01~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/closureReferenceCycle02@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/closureReferenceCycle02@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/closureReferenceCycle02~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/closureReferenceCycle02~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/computedProperties@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/computedProperties@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/computedProperties~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/computedProperties~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/coordinateGraphComplex@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/coordinateGraphComplex@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/coordinateGraphComplex~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/coordinateGraphComplex~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/coordinateGraphMedium@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/coordinateGraphMedium@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/coordinateGraphMedium~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/coordinateGraphMedium~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/coordinateGraphSimple@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/coordinateGraphSimple@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/coordinateGraphSimple~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/coordinateGraphSimple~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/cover_opensource.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/cover_opensource.jpg -------------------------------------------------------------------------------- /TSPL.docc/Assets/initializerDelegation01@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/initializerDelegation01@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/initializerDelegation01~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/initializerDelegation01~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/initializerDelegation02@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/initializerDelegation02@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/initializerDelegation02~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/initializerDelegation02~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/initializersExample01@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/initializersExample01@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/initializersExample01~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/initializersExample01~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/initializersExample02@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/initializersExample02@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/initializersExample02~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/initializersExample02~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/initializersExample03@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/initializersExample03@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/initializersExample03~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/initializersExample03~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/macro-ast-input@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/macro-ast-input@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/macro-ast-input~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/macro-ast-input~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/macro-ast-original@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/macro-ast-original@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/macro-ast-original~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/macro-ast-original~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/macro-ast-output@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/macro-ast-output@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/macro-ast-output~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/macro-ast-output~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/macro-ast-result@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/macro-ast-result@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/macro-ast-result~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/macro-ast-result~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/macro-expansion-full@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/macro-expansion-full@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/macro-expansion-full~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/macro-expansion-full~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/macro-expansion@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/macro-expansion@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/macro-expansion~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/macro-expansion~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/memory_increment@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/memory_increment@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/memory_increment~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/memory_increment~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/memory_map@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/memory_map@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/memory_mapInPlace@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/memory_mapInPlace@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/memory_mapInPlace~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/memory_mapInPlace~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/memory_map~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/memory_map~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/memory_share_health_maria@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/memory_share_health_maria@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/memory_share_health_maria~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/memory_share_health_maria~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/memory_share_health_oscar@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/memory_share_health_oscar@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/memory_share_health_oscar~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/memory_share_health_oscar~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/memory_shopping@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/memory_shopping@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/memory_shopping~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/memory_shopping~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/multilineStringWhitespace@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/multilineStringWhitespace@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/multilineStringWhitespace~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/multilineStringWhitespace~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/overflowAddition@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/overflowAddition@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/overflowAddition~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/overflowAddition~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/overflowSignedSubtraction@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/overflowSignedSubtraction@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/overflowSignedSubtraction~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/overflowSignedSubtraction~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/overflowUnsignedSubtraction@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/overflowUnsignedSubtraction@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/overflowUnsignedSubtraction~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/overflowUnsignedSubtraction~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/referenceCycle01@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/referenceCycle01@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/referenceCycle01~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/referenceCycle01~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/referenceCycle02@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/referenceCycle02@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/referenceCycle02~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/referenceCycle02~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/referenceCycle03@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/referenceCycle03@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/referenceCycle03~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/referenceCycle03~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/remainderInteger@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/remainderInteger@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/remainderInteger~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/remainderInteger~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/setEulerDiagram@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/setEulerDiagram@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/setEulerDiagram~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/setEulerDiagram~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/setVennDiagram@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/setVennDiagram@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/setVennDiagram~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/setVennDiagram~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/sharedStateClass@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/sharedStateClass@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/sharedStateClass~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/sharedStateClass~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/sharedStateStruct@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/sharedStateStruct@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/sharedStateStruct~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/sharedStateStruct~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/snakesAndLadders@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/snakesAndLadders@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/snakesAndLadders~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/snakesAndLadders~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/stackPoppedOneString@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/stackPoppedOneString@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/stackPoppedOneString~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/stackPoppedOneString~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/stackPushPop@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/stackPushPop@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/stackPushPop~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/stackPushPop~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/stackPushedFourStrings@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/stackPushedFourStrings@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/stackPushedFourStrings~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/stackPushedFourStrings~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/staticPropertiesVUMeter@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/staticPropertiesVUMeter@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/staticPropertiesVUMeter~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/staticPropertiesVUMeter~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/stringSubstring@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/stringSubstring@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/stringSubstring~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/stringSubstring~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/subscriptMatrix01@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/subscriptMatrix01@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/subscriptMatrix01~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/subscriptMatrix01~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/subscriptMatrix02@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/subscriptMatrix02@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/subscriptMatrix02~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/subscriptMatrix02~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/twoPhaseInitialization01@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/twoPhaseInitialization01@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/twoPhaseInitialization01~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/twoPhaseInitialization01~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/twoPhaseInitialization02@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/twoPhaseInitialization02@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/twoPhaseInitialization02~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/twoPhaseInitialization02~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/unownedOptionalReference@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/unownedOptionalReference@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/unownedOptionalReference~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/unownedOptionalReference~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/unownedReference01@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/unownedReference01@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/unownedReference01~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/unownedReference01~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/unownedReference02@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/unownedReference02@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/unownedReference02~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/unownedReference02~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/vectorAddition@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/vectorAddition@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/vectorAddition~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/vectorAddition~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/weakReference01@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/weakReference01@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/weakReference01~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/weakReference01~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/weakReference02@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/weakReference02@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/weakReference02~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/weakReference02~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/weakReference03@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/weakReference03@2x.png -------------------------------------------------------------------------------- /TSPL.docc/Assets/weakReference03~dark@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swiftlang/swift-book/a904b1d2aa88fe5db6deb2a055fbc572b18f08cb/TSPL.docc/Assets/weakReference03~dark@2x.png -------------------------------------------------------------------------------- /TSPL.docc/GuidedTour/AboutSwift.md: -------------------------------------------------------------------------------- 1 | # About Swift 2 | 3 | Understand the high-level goals of the language. 4 | 5 | Swift is a fantastic way to write software 6 | for phones, tablets, desktops, servers, 7 | or anything else that runs code. 8 | It's a safe and fast programming language 9 | that combines the best in modern language thinking 10 | with wisdom from a diverse open source community. 11 | 12 | Swift is friendly to new programmers, 13 | without sacrificing the power and flexibility 14 | that experienced programmers need. 15 | It's an industrial-quality programming language 16 | that's as expressive and enjoyable as a scripting language. 17 | The compiler is optimized for performance 18 | and the language is optimized for development, 19 | without compromising on either. 20 | 21 | Swift defines away large classes of common programming errors 22 | by adopting modern programming patterns: 23 | 24 | - Variables are always initialized before use. 25 | - Array indices are checked for out-of-bounds errors. 26 | - Integers are checked for overflow. 27 | - Optionals ensure that `nil` values are handled explicitly. 28 | - Memory is managed automatically. 29 | - Error handling allows controlled recovery from unexpected failures. 30 | 31 | Swift code is compiled and optimized to get the most out of modern hardware. 32 | The syntax and standard library have been designed 33 | based on the guiding principle that 34 | the obvious way to write your code should also perform the best. 35 | Its combination of safety and speed make Swift an excellent choice for 36 | everything from "Hello, world!" to an entire operating system. 37 | 38 | Swift combines a modern, lightweight syntax 39 | that's familiar for developers coming from other popular languages 40 | with powerful features like type inference and pattern matching, 41 | allowing complex ideas to be expressed in a clear and concise manner. 42 | As a result, code is easier to read, write, and maintain. 43 | 44 | Swift continues to evolve with thoughtful new features and powerful capabilities. 45 | The goals for Swift are ambitious. 46 | We can’t wait to see what you create with it. 47 | 48 | 57 | -------------------------------------------------------------------------------- /TSPL.docc/GuidedTour/Compatibility.md: -------------------------------------------------------------------------------- 1 | # Version Compatibility 2 | 3 | Learn what functionality is available in older language modes. 4 | 5 | This book describes Swift 6.1, 6 | the default version of Swift that's included in Xcode 16.3. 7 | You can use the Swift 6.1 compiler to build code 8 | that's written in Swift 6.1, Swift 5, Swift 4.2, or Swift 4. 9 | 10 | When you use the Swift 6.1 compiler 11 | to build code that uses the Swift 5 language mode, 12 | you can use the new features from Swift 6.1 --- 13 | they're enabled either by default or by an upcoming feature flag. 14 | However, to enable strict concurrency checking, 15 | you need to upgrade to the Swift 6.1 language mode. 16 | 17 | In addition, 18 | when you use Xcode 15.3 to build Swift 4 and Swift 4.2 code, 19 | most Swift 5 functionality is still available. 20 | That said, 21 | the following changes are available only to code 22 | that uses the Swift 5 language mode: 23 | 24 | - Functions that return an opaque type require the Swift 5.1 runtime. 25 | - The `try?` expression doesn't introduce an extra level of optionality 26 | to expressions that already return optionals. 27 | - Large integer literal initialization expressions are inferred 28 | to be of the correct integer type. 29 | For example, `UInt64(0xffff_ffff_ffff_ffff)` evaluates to the correct value 30 | rather than overflowing. 31 | 32 | Concurrency requires the Swift 5 language mode 33 | and a version of the Swift standard library 34 | that provides the corresponding concurrency types. 35 | On Apple platforms, set a deployment target 36 | of at least iOS 13, macOS 10.15, tvOS 13, watchOS 6, or visionOS 1. 37 | 38 | A target written in Swift 6.1 can depend on 39 | a target that's written in Swift 5, Swift 4.2 or Swift 4, 40 | and vice versa. 41 | This means, if you have a large project 42 | that's divided into multiple frameworks, 43 | you can migrate your code to a newer language version 44 | one framework at a time. 45 | 46 | 55 | -------------------------------------------------------------------------------- /TSPL.docc/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDisplayName 6 | The Swift Programming Language 7 | CFBundleIdentifier 8 | org.swift.tspl 9 | CDDefaultCodeListingLanguage 10 | swift 11 | CDDefaultModuleKind 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /TSPL.docc/LanguageGuide/Deinitialization.md: -------------------------------------------------------------------------------- 1 | # Deinitialization 2 | 3 | Release resources that require custom cleanup. 4 | 5 | A *deinitializer* is called immediately before a class instance is deallocated. 6 | You write deinitializers with the `deinit` keyword, 7 | similar to how initializers are written with the `init` keyword. 8 | Deinitializers are only available on class types. 9 | 10 | ## How Deinitialization Works 11 | 12 | Swift automatically deallocates your instances when they're no longer needed, 13 | to free up resources. 14 | Swift handles the memory management of instances through 15 | *automatic reference counting* (*ARC*), 16 | as described in . 17 | Typically you don't need to perform manual cleanup when your instances are deallocated. 18 | However, when you are working with your own resources, 19 | you might need to perform some additional cleanup yourself. 20 | For example, if you create a custom class to open a file and write some data to it, 21 | you might need to close the file before the class instance is deallocated. 22 | 23 | Class definitions can have at most one deinitializer per class. 24 | The deinitializer doesn't take any parameters 25 | and is written without parentheses: 26 | 27 | ```swift 28 | deinit { 29 | // perform the deinitialization 30 | } 31 | ``` 32 | 33 | 44 | 45 | Deinitializers are called automatically, just before instance deallocation takes place. 46 | You aren't allowed to call a deinitializer yourself. 47 | Superclass deinitializers are inherited by their subclasses, 48 | and the superclass deinitializer is called automatically at the end of 49 | a subclass deinitializer implementation. 50 | Superclass deinitializers are always called, 51 | even if a subclass doesn't provide its own deinitializer. 52 | 53 | Because an instance isn't deallocated until after its deinitializer is called, 54 | a deinitializer can access all properties of the instance it's called on 55 | and can modify its behavior based on those properties 56 | (such as looking up the name of a file that needs to be closed). 57 | 58 | ## Deinitializers in Action 59 | 60 | Here's an example of a deinitializer in action. 61 | This example defines two new types, `Bank` and `Player`, for a simple game. 62 | The `Bank` class manages a made-up currency, 63 | which can never have more than 10,000 coins in circulation. 64 | There can only ever be one `Bank` in the game, 65 | and so the `Bank` is implemented as a class with type properties and methods 66 | to store and manage its current state: 67 | 68 | ```swift 69 | class Bank { 70 | static var coinsInBank = 10_000 71 | static func distribute(coins numberOfCoinsRequested: Int) -> Int { 72 | let numberOfCoinsToVend = min(numberOfCoinsRequested, coinsInBank) 73 | coinsInBank -= numberOfCoinsToVend 74 | return numberOfCoinsToVend 75 | } 76 | static func receive(coins: Int) { 77 | coinsInBank += coins 78 | } 79 | } 80 | ``` 81 | 82 | 99 | 100 | `Bank` keeps track of the current number of coins it holds with its `coinsInBank` property. 101 | It also offers two methods --- `distribute(coins:)` and `receive(coins:)` --- 102 | to handle the distribution and collection of coins. 103 | 104 | The `distribute(coins:)` method checks that there are enough coins in the bank before distributing them. 105 | If there aren't enough coins, 106 | `Bank` returns a smaller number than the number that was requested 107 | (and returns zero if no coins are left in the bank). 108 | It returns an integer value to indicate the actual number of coins that were provided. 109 | 110 | The `receive(coins:)` method simply adds the received number of coins back into the bank's coin store. 111 | 112 | The `Player` class describes a player in the game. 113 | Each player has a certain number of coins stored in their purse at any time. 114 | This is represented by the player's `coinsInPurse` property: 115 | 116 | ```swift 117 | class Player { 118 | var coinsInPurse: Int 119 | init(coins: Int) { 120 | coinsInPurse = Bank.distribute(coins: coins) 121 | } 122 | func win(coins: Int) { 123 | coinsInPurse += Bank.distribute(coins: coins) 124 | } 125 | deinit { 126 | Bank.receive(coins: coinsInPurse) 127 | } 128 | } 129 | ``` 130 | 131 | 149 | 150 | Each `Player` instance is initialized with a starting allowance of 151 | a specified number of coins from the bank during initialization, 152 | although a `Player` instance may receive fewer than that number 153 | if not enough coins are available. 154 | 155 | The `Player` class defines a `win(coins:)` method, 156 | which retrieves a certain number of coins from the bank 157 | and adds them to the player's purse. 158 | The `Player` class also implements a deinitializer, 159 | which is called just before a `Player` instance is deallocated. 160 | Here, the deinitializer simply returns all of the player's coins to the bank: 161 | 162 | ```swift 163 | var playerOne: Player? = Player(coins: 100) 164 | print("A new player has joined the game with \(playerOne!.coinsInPurse) coins") 165 | // Prints "A new player has joined the game with 100 coins" 166 | print("There are now \(Bank.coinsInBank) coins left in the bank") 167 | // Prints "There are now 9900 coins left in the bank" 168 | ``` 169 | 170 | 181 | 182 | A new `Player` instance is created, with a request for 100 coins if they're available. 183 | This `Player` instance is stored in an optional `Player` variable called `playerOne`. 184 | An optional variable is used here, because players can leave the game at any point. 185 | The optional lets you track whether there's currently a player in the game. 186 | 187 | Because `playerOne` is an optional, it's qualified with an exclamation point (`!`) 188 | when its `coinsInPurse` property is accessed to print its default number of coins, 189 | and whenever its `win(coins:)` method is called: 190 | 191 | ```swift 192 | playerOne!.win(coins: 2_000) 193 | print("PlayerOne won 2000 coins & now has \(playerOne!.coinsInPurse) coins") 194 | // Prints "PlayerOne won 2000 coins & now has 2100 coins" 195 | print("The bank now only has \(Bank.coinsInBank) coins left") 196 | // Prints "The bank now only has 7900 coins left" 197 | ``` 198 | 199 | 210 | 211 | Here, the player has won 2,000 coins. 212 | The player's purse now contains 2,100 coins, 213 | and the bank has only 7,900 coins left. 214 | 215 | ```swift 216 | playerOne = nil 217 | print("PlayerOne has left the game") 218 | // Prints "PlayerOne has left the game" 219 | print("The bank now has \(Bank.coinsInBank) coins") 220 | // Prints "The bank now has 10000 coins" 221 | ``` 222 | 223 | 234 | 235 | The player has now left the game. 236 | This is indicated by setting the optional `playerOne` variable to `nil`, 237 | meaning “no `Player` instance.” 238 | At the point that this happens, 239 | the `playerOne` variable's reference to the `Player` instance is broken. 240 | No other properties or variables are still referring to the `Player` instance, 241 | and so it's deallocated in order to free up its memory. 242 | Just before this happens, its deinitializer is called automatically, 243 | and its coins are returned to the bank. 244 | 245 | 254 | -------------------------------------------------------------------------------- /TSPL.docc/LanguageGuide/Extensions.md: -------------------------------------------------------------------------------- 1 | # Extensions 2 | 3 | Add functionality to an existing type. 4 | 5 | *Extensions* add new functionality to an existing 6 | class, structure, enumeration, or protocol type. 7 | This includes the ability to extend types 8 | for which you don't have access to the original source code 9 | (known as *retroactive modeling*). 10 | Extensions are similar to categories in Objective-C. 11 | (Unlike Objective-C categories, Swift extensions don't have names.) 12 | 13 | Extensions in Swift can: 14 | 15 | - Add computed instance properties and computed type properties 16 | - Define instance methods and type methods 17 | - Provide new initializers 18 | - Define subscripts 19 | - Define and use new nested types 20 | - Make an existing type conform to a protocol 21 | 22 | In Swift, 23 | you can even extend a protocol to provide implementations of its requirements 24 | or add additional functionality that conforming types can take advantage of. 25 | For more details, see . 26 | 27 | > Note: Extensions can add new functionality to a type, 28 | > but they can't override existing functionality. 29 | 30 | 77 | 78 | ## Extension Syntax 79 | 80 | Declare extensions with the `extension` keyword: 81 | 82 | ```swift 83 | extension SomeType { 84 | // new functionality to add to SomeType goes here 85 | } 86 | ``` 87 | 88 | 98 | 99 | An extension can extend an existing type to make it adopt one or more protocols. 100 | To add protocol conformance, 101 | you write the protocol names 102 | the same way as you write them for a class or structure: 103 | 104 | ```swift 105 | extension SomeType: SomeProtocol, AnotherProtocol { 106 | // implementation of protocol requirements goes here 107 | } 108 | ``` 109 | 110 | 121 | 122 | Adding protocol conformance in this way is described in 123 | . 124 | 125 | An extension can be used to extend an existing generic type, 126 | as described in . 127 | You can also extend a generic type to conditionally add functionality, 128 | as described in . 129 | 130 | > Note: If you define an extension to add new functionality to an existing type, 131 | > the new functionality will be available on all existing instances of that type, 132 | > even if they were created before the extension was defined. 133 | 134 | ## Computed Properties 135 | 136 | Extensions can add computed instance properties and computed type properties to existing types. 137 | This example adds five computed instance properties to Swift's built-in `Double` type, 138 | to provide basic support for working with distance units: 139 | 140 | ```swift 141 | extension Double { 142 | var km: Double { return self * 1_000.0 } 143 | var m: Double { return self } 144 | var cm: Double { return self / 100.0 } 145 | var mm: Double { return self / 1_000.0 } 146 | var ft: Double { return self / 3.28084 } 147 | } 148 | let oneInch = 25.4.mm 149 | print("One inch is \(oneInch) meters") 150 | // Prints "One inch is 0.0254 meters" 151 | let threeFeet = 3.ft 152 | print("Three feet is \(threeFeet) meters") 153 | // Prints "Three feet is 0.914399970739201 meters" 154 | ``` 155 | 156 | 175 | 176 | These computed properties express that a `Double` value 177 | should be considered as a certain unit of length. 178 | Although they're implemented as computed properties, 179 | the names of these properties can be appended to 180 | a floating-point literal value with dot syntax, 181 | as a way to use that literal value to perform distance conversions. 182 | 183 | In this example, a `Double` value of `1.0` is considered to represent “one meter”. 184 | This is why the `m` computed property returns `self` --- 185 | the expression `1.m` is considered to calculate a `Double` value of `1.0`. 186 | 187 | Other units require some conversion to be expressed as a value measured in meters. 188 | One kilometer is the same as 1,000 meters, 189 | so the `km` computed property multiplies the value by `1_000.00` 190 | to convert into a number expressed in meters. 191 | Similarly, there are 3.28084 feet in a meter, 192 | and so the `ft` computed property divides the underlying `Double` value 193 | by `3.28084`, to convert it from feet to meters. 194 | 195 | These properties are read-only computed properties, 196 | and so they're expressed without the `get` keyword, for brevity. 197 | Their return value is of type `Double`, 198 | and can be used within mathematical calculations wherever a `Double` is accepted: 199 | 200 | ```swift 201 | let aMarathon = 42.km + 195.m 202 | print("A marathon is \(aMarathon) meters long") 203 | // Prints "A marathon is 42195.0 meters long" 204 | ``` 205 | 206 | 215 | 216 | > Note: Extensions can add new computed properties, but they can't add stored properties, 217 | > or add property observers to existing properties. 218 | 219 | 230 | 231 | 234 | 235 | ## Initializers 236 | 237 | Extensions can add new initializers to existing types. 238 | This enables you to extend other types to accept 239 | your own custom types as initializer parameters, 240 | or to provide additional initialization options 241 | that were not included as part of the type's original implementation. 242 | 243 | Extensions can add new convenience initializers to a class, 244 | but they can't add new designated initializers or deinitializers to a class. 245 | Designated initializers and deinitializers 246 | must always be provided by the original class implementation. 247 | 248 | If you use an extension to add an initializer to a value type that provides 249 | default values for all of its stored properties 250 | and doesn't define any custom initializers, 251 | you can call the default initializer and memberwise initializer for that value type 252 | from within your extension's initializer. 253 | This wouldn't be the case if you had written the initializer 254 | as part of the value type's original implementation, 255 | as described in . 256 | 257 | If you use an extension to add an initializer to a structure 258 | that was declared in another module, 259 | the new initializer can't access `self` until it calls 260 | an initializer from the defining module. 261 | 262 | The example below defines a custom `Rect` structure to represent a geometric rectangle. 263 | The example also defines two supporting structures called `Size` and `Point`, 264 | both of which provide default values of `0.0` for all of their properties: 265 | 266 | ```swift 267 | struct Size { 268 | var width = 0.0, height = 0.0 269 | } 270 | struct Point { 271 | var x = 0.0, y = 0.0 272 | } 273 | struct Rect { 274 | var origin = Point() 275 | var size = Size() 276 | } 277 | ``` 278 | 279 | 295 | 296 | Because the `Rect` structure provides default values for all of its properties, 297 | it receives a default initializer and a memberwise initializer automatically, 298 | as described in . 299 | These initializers can be used to create new `Rect` instances: 300 | 301 | ```swift 302 | let defaultRect = Rect() 303 | let memberwiseRect = Rect(origin: Point(x: 2.0, y: 2.0), 304 | size: Size(width: 5.0, height: 5.0)) 305 | ``` 306 | 307 | 316 | 317 | You can extend the `Rect` structure to provide an additional initializer 318 | that takes a specific center point and size: 319 | 320 | ```swift 321 | extension Rect { 322 | init(center: Point, size: Size) { 323 | let originX = center.x - (size.width / 2) 324 | let originY = center.y - (size.height / 2) 325 | self.init(origin: Point(x: originX, y: originY), size: size) 326 | } 327 | } 328 | ``` 329 | 330 | 343 | 344 | This new initializer starts by calculating an appropriate origin point based on 345 | the provided `center` point and `size` value. 346 | The initializer then calls the structure's automatic memberwise initializer 347 | `init(origin:size:)`, which stores the new origin and size values 348 | in the appropriate properties: 349 | 350 | ```swift 351 | let centerRect = Rect(center: Point(x: 4.0, y: 4.0), 352 | size: Size(width: 3.0, height: 3.0)) 353 | // centerRect's origin is (2.5, 2.5) and its size is (3.0, 3.0) 354 | ``` 355 | 356 | 366 | 367 | > Note: If you provide a new initializer with an extension, 368 | > you are still responsible for making sure that each instance is fully initialized 369 | > once the initializer completes. 370 | 371 | ## Methods 372 | 373 | Extensions can add new instance methods and type methods to existing types. 374 | The following example adds a new instance method called `repetitions` to the `Int` type: 375 | 376 | ```swift 377 | extension Int { 378 | func repetitions(task: () -> Void) { 379 | for _ in 0.. extension Int { 391 | func repetitions(task: () -> Void) { 392 | for _ in 0.. 399 | 400 | The `repetitions(task:)` method takes a single argument of type `() -> Void`, 401 | which indicates a function that has no parameters and doesn't return a value. 402 | 403 | After defining this extension, 404 | you can call the `repetitions(task:)` method on any integer 405 | to perform a task that many number of times: 406 | 407 | ```swift 408 | 3.repetitions { 409 | print("Hello!") 410 | } 411 | // Hello! 412 | // Hello! 413 | // Hello! 414 | ``` 415 | 416 | 428 | 429 | ### Mutating Instance Methods 430 | 431 | Instance methods added with an extension can also modify (or *mutate*) the instance itself. 432 | Structure and enumeration methods that modify `self` or its properties 433 | must mark the instance method as `mutating`, 434 | just like mutating methods from an original implementation. 435 | 436 | The example below adds a new mutating method called `square` to Swift's `Int` type, 437 | which squares the original value: 438 | 439 | ```swift 440 | extension Int { 441 | mutating func square() { 442 | self = self * self 443 | } 444 | } 445 | var someInt = 3 446 | someInt.square() 447 | // someInt is now 9 448 | ``` 449 | 450 | 465 | 466 | ## Subscripts 467 | 468 | Extensions can add new subscripts to an existing type. 469 | This example adds an integer subscript to Swift's built-in `Int` type. 470 | This subscript `[n]` returns the decimal digit `n` places in 471 | from the right of the number: 472 | 473 | - `123456789[0]` returns `9` 474 | - `123456789[1]` returns `8` 475 | 476 | …and so on: 477 | 478 | ```swift 479 | extension Int { 480 | subscript(digitIndex: Int) -> Int { 481 | var decimalBase = 1 482 | for _ in 0.. extension Int { 503 | subscript(digitIndex: Int) -> Int { 504 | var decimalBase = 1 505 | for _ in 0..> let r0 = 512 | -> 746381295[0] 513 | /> returns \(r0) 514 | > let r1 = 516 | -> 746381295[1] 517 | /> returns \(r1) 518 | > let r2 = 520 | -> 746381295[2] 521 | /> returns \(r2) 522 | > let r3 = 524 | -> 746381295[8] 525 | /> returns \(r3) 526 | 529 | 530 | 534 | 535 | 540 | 541 | If the `Int` value doesn't have enough digits for the requested index, 542 | the subscript implementation returns `0`, 543 | as if the number had been padded with zeros to the left: 544 | 545 | ```swift 546 | 746381295[9] 547 | // returns 0, as if you had requested: 548 | 0746381295[9] 549 | ``` 550 | 551 | 563 | 564 | 567 | 568 | 572 | 573 | ## Nested Types 574 | 575 | Extensions can add new nested types to existing classes, structures, and enumerations: 576 | 577 | ```swift 578 | extension Int { 579 | enum Kind { 580 | case negative, zero, positive 581 | } 582 | var kind: Kind { 583 | switch self { 584 | case 0: 585 | return .zero 586 | case let x where x > 0: 587 | return .positive 588 | default: 589 | return .negative 590 | } 591 | } 592 | } 593 | ``` 594 | 595 | 616 | 617 | This example adds a new nested enumeration to `Int`. 618 | This enumeration, called `Kind`, 619 | expresses the kind of number that a particular integer represents. 620 | Specifically, it expresses whether the number is 621 | negative, zero, or positive. 622 | 623 | This example also adds a new computed instance property to `Int`, 624 | called `kind`, 625 | which returns the appropriate `Kind` enumeration case for that integer. 626 | 627 | The nested enumeration can now be used with any `Int` value: 628 | 629 | ```swift 630 | func printIntegerKinds(_ numbers: [Int]) { 631 | for number in numbers { 632 | switch number.kind { 633 | case .negative: 634 | print("- ", terminator: "") 635 | case .zero: 636 | print("0 ", terminator: "") 637 | case .positive: 638 | print("+ ", terminator: "") 639 | } 640 | } 641 | print("") 642 | } 643 | printIntegerKinds([3, 19, -27, 0, -6, 0, 7]) 644 | // Prints "+ + - 0 - 0 + " 645 | ``` 646 | 647 | 669 | 670 | 673 | 674 | This function, `printIntegerKinds(_:)`, 675 | takes an input array of `Int` values and iterates over those values in turn. 676 | For each integer in the array, 677 | the function considers the `kind` computed property for that integer, 678 | and prints an appropriate description. 679 | 680 | > Note: `number.kind` is already known to be of type `Int.Kind`. 681 | > Because of this, all of the `Int.Kind` case values 682 | > can be written in shorthand form inside the `switch` statement, 683 | > such as `.negative` rather than `Int.Kind.negative`. 684 | 685 | 694 | -------------------------------------------------------------------------------- /TSPL.docc/LanguageGuide/Inheritance.md: -------------------------------------------------------------------------------- 1 | # Inheritance 2 | 3 | Subclass to add or override functionality. 4 | 5 | A class can *inherit* methods, properties, and other characteristics 6 | from another class. 7 | When one class inherits from another, 8 | the inheriting class is known as a *subclass*, 9 | and the class it inherits from is known as its *superclass*. 10 | Inheritance is a fundamental behavior that differentiates classes 11 | from other types in Swift. 12 | 13 | Classes in Swift can call and access 14 | methods, properties, and subscripts belonging to their superclass 15 | and can provide their own overriding versions of those methods, properties, and subscripts 16 | to refine or modify their behavior. 17 | Swift helps to ensure your overrides are correct 18 | by checking that the override definition has a matching superclass definition. 19 | 20 | Classes can also add property observers to inherited properties 21 | in order to be notified when the value of a property changes. 22 | Property observers can be added to any property, 23 | regardless of whether it was originally defined as a stored or computed property. 24 | 25 | ## Defining a Base Class 26 | 27 | Any class that doesn't inherit from another class is known as a *base class*. 28 | 29 | > Note: Swift classes don't inherit from a universal base class. 30 | > Classes you define without specifying a superclass 31 | > automatically become base classes for you to build upon. 32 | 33 | The example below defines a base class called `Vehicle`. 34 | This base class defines a stored property called `currentSpeed`, 35 | with a default value of `0.0` (inferring a property type of `Double`). 36 | The `currentSpeed` property's value is used by 37 | a read-only computed `String` property called `description` 38 | to create a description of the vehicle. 39 | 40 | The `Vehicle` base class also defines a method called `makeNoise`. 41 | This method doesn't actually do anything for a base `Vehicle` instance, 42 | but will be customized by subclasses of `Vehicle` later on: 43 | 44 | ```swift 45 | class Vehicle { 46 | var currentSpeed = 0.0 47 | var description: String { 48 | return "traveling at \(currentSpeed) miles per hour" 49 | } 50 | func makeNoise() { 51 | // do nothing - an arbitrary vehicle doesn't necessarily make a noise 52 | } 53 | } 54 | ``` 55 | 56 | 71 | 72 | You create a new instance of `Vehicle` with *initializer syntax*, 73 | which is written as a type name followed by empty parentheses: 74 | 75 | ```swift 76 | let someVehicle = Vehicle() 77 | ``` 78 | 79 | 86 | 87 | Having created a new `Vehicle` instance, 88 | you can access its `description` property to print 89 | a human-readable description of the vehicle's current speed: 90 | 91 | ```swift 92 | print("Vehicle: \(someVehicle.description)") 93 | // Vehicle: traveling at 0.0 miles per hour 94 | ``` 95 | 96 | 104 | 105 | The `Vehicle` class defines common characteristics for an arbitrary vehicle, 106 | but isn't much use in itself. 107 | To make it more useful, 108 | you need to refine it to describe more specific kinds of vehicles. 109 | 110 | ## Subclassing 111 | 112 | *Subclassing* is the act of basing a new class on an existing class. 113 | The subclass inherits characteristics from the existing class, which you can then refine. 114 | You can also add new characteristics to the subclass. 115 | 116 | To indicate that a subclass has a superclass, 117 | write the subclass name before the superclass name, 118 | separated by a colon: 119 | 120 | ```swift 121 | class SomeSubclass: SomeSuperclass { 122 | // subclass definition goes here 123 | } 124 | ``` 125 | 126 | 136 | 137 | The following example defines a subclass called `Bicycle`, 138 | with a superclass of `Vehicle`: 139 | 140 | ```swift 141 | class Bicycle: Vehicle { 142 | var hasBasket = false 143 | } 144 | ``` 145 | 146 | 155 | 156 | The new `Bicycle` class automatically gains all of the characteristics of `Vehicle`, 157 | such as its `currentSpeed` and `description` properties and its `makeNoise()` method. 158 | 159 | In addition to the characteristics it inherits, 160 | the `Bicycle` class defines a new stored property, 161 | `hasBasket`, with a default value of `false` 162 | (inferring a type of `Bool` for the property). 163 | 164 | By default, any new `Bicycle` instance you create will not have a basket. 165 | You can set the `hasBasket` property to `true` for a particular `Bicycle` instance 166 | after that instance is created: 167 | 168 | ```swift 169 | let bicycle = Bicycle() 170 | bicycle.hasBasket = true 171 | ``` 172 | 173 | 181 | 182 | You can also modify the inherited `currentSpeed` property of a `Bicycle` instance, 183 | and query the instance's inherited `description` property: 184 | 185 | ```swift 186 | bicycle.currentSpeed = 15.0 187 | print("Bicycle: \(bicycle.description)") 188 | // Bicycle: traveling at 15.0 miles per hour 189 | ``` 190 | 191 | 200 | 201 | Subclasses can themselves be subclassed. 202 | The next example creates a subclass of `Bicycle` for a two-seater bicycle 203 | known as a “tandem”: 204 | 205 | ```swift 206 | class Tandem: Bicycle { 207 | var currentNumberOfPassengers = 0 208 | } 209 | ``` 210 | 211 | 220 | 221 | `Tandem` inherits all of the properties and methods from `Bicycle`, 222 | which in turn inherits all of the properties and methods from `Vehicle`. 223 | The `Tandem` subclass also adds a new stored property called `currentNumberOfPassengers`, 224 | with a default value of `0`. 225 | 226 | If you create an instance of `Tandem`, 227 | you can work with any of its new and inherited properties, 228 | and query the read-only `description` property it inherits from `Vehicle`: 229 | 230 | ```swift 231 | let tandem = Tandem() 232 | tandem.hasBasket = true 233 | tandem.currentNumberOfPassengers = 2 234 | tandem.currentSpeed = 22.0 235 | print("Tandem: \(tandem.description)") 236 | // Tandem: traveling at 22.0 miles per hour 237 | ``` 238 | 239 | 251 | 252 | ## Overriding 253 | 254 | A subclass can provide its own custom implementation of 255 | an instance method, type method, instance property, type property, or subscript 256 | that it would otherwise inherit from a superclass. 257 | This is known as *overriding*. 258 | 259 | To override a characteristic that would otherwise be inherited, 260 | you prefix your overriding definition with the `override` keyword. 261 | Doing so clarifies that you intend to provide an override 262 | and haven't provided a matching definition by mistake. 263 | Overriding by accident can cause unexpected behavior, 264 | and any overrides without the `override` keyword are 265 | diagnosed as an error when your code is compiled. 266 | 267 | The `override` keyword also prompts the Swift compiler 268 | to check that your overriding class's superclass (or one of its parents) 269 | has a declaration that matches the one you provided for the override. 270 | This check ensures that your overriding definition is correct. 271 | 272 | ### Accessing Superclass Methods, Properties, and Subscripts 273 | 274 | When you provide a method, property, or subscript override for a subclass, 275 | it's sometimes useful to use the existing superclass implementation 276 | as part of your override. 277 | For example, you can refine the behavior of that existing implementation, 278 | or store a modified value in an existing inherited variable. 279 | 280 | Where this is appropriate, 281 | you access the superclass version of a method, property, or subscript 282 | by using the `super` prefix: 283 | 284 | - An overridden method named `someMethod()` can call the superclass version of `someMethod()` 285 | by calling `super.someMethod()` within the overriding method implementation. 286 | - An overridden property called `someProperty` can access the superclass version of `someProperty` 287 | as `super.someProperty` within the overriding getter or setter implementation. 288 | - An overridden subscript for `someIndex` can access the superclass version of the same subscript 289 | as `super[someIndex]` from within the overriding subscript implementation. 290 | 291 | ### Overriding Methods 292 | 293 | You can override an inherited instance or type method 294 | to provide a tailored or alternative implementation of the method within your subclass. 295 | 296 | The following example defines a new subclass of `Vehicle` called `Train`, 297 | which overrides the `makeNoise()` method that `Train` inherits from `Vehicle`: 298 | 299 | ```swift 300 | class Train: Vehicle { 301 | override func makeNoise() { 302 | print("Choo Choo") 303 | } 304 | } 305 | ``` 306 | 307 | 318 | 319 | If you create a new instance of `Train` and call its `makeNoise()` method, 320 | you can see that the `Train` subclass version of the method is called: 321 | 322 | ```swift 323 | let train = Train() 324 | train.makeNoise() 325 | // Prints "Choo Choo" 326 | ``` 327 | 328 | 337 | 338 | ### Overriding Properties 339 | 340 | You can override an inherited instance or type property 341 | to provide your own custom getter and setter for that property, 342 | or to add property observers to enable the overriding property 343 | to observe when the underlying property value changes. 344 | 345 | #### Overriding Property Getters and Setters 346 | 347 | You can provide a custom getter (and setter, if appropriate) 348 | to override *any* inherited property, 349 | regardless of whether the inherited property is implemented as 350 | a stored or computed property at source. 351 | The stored or computed nature of an inherited property isn't known by a subclass --- 352 | it only knows that the inherited property has a certain name and type. 353 | You must always state both the name and the type of the property you are overriding, 354 | to enable the compiler to check that your override matches 355 | a superclass property with the same name and type. 356 | 357 | You can present an inherited read-only property as a read-write property 358 | by providing both a getter and a setter in your subclass property override. 359 | You can't, however, present an inherited read-write property as a read-only property. 360 | 361 | > Note: If you provide a setter as part of a property override, 362 | > you must also provide a getter for that override. 363 | > If you don't want to modify the inherited property's value within the overriding getter, 364 | > you can simply pass through the inherited value 365 | > by returning `super.someProperty` from the getter, 366 | > where `someProperty` is the name of the property you are overriding. 367 | 368 | The following example defines a new class called `Car`, 369 | which is a subclass of `Vehicle`. 370 | The `Car` class introduces a new stored property called `gear`, 371 | with a default integer value of `1`. 372 | The `Car` class also overrides the `description` property it inherits from `Vehicle`, 373 | to provide a custom description that includes the current gear: 374 | 375 | ```swift 376 | class Car: Vehicle { 377 | var gear = 1 378 | override var description: String { 379 | return super.description + " in gear \(gear)" 380 | } 381 | } 382 | ``` 383 | 384 | 396 | 397 | The override of the `description` property starts by calling `super.description`, 398 | which returns the `Vehicle` class's `description` property. 399 | The `Car` class's version of `description` then adds some extra text onto 400 | the end of this description to provide information about the current gear. 401 | 402 | If you create an instance of the `Car` class 403 | and set its `gear` and `currentSpeed` properties, 404 | you can see that its `description` property returns 405 | the tailored description defined within the `Car` class: 406 | 407 | ```swift 408 | let car = Car() 409 | car.currentSpeed = 25.0 410 | car.gear = 3 411 | print("Car: \(car.description)") 412 | // Car: traveling at 25.0 miles per hour in gear 3 413 | ``` 414 | 415 | 426 | 427 | #### Overriding Property Observers 428 | 429 | You can use property overriding to add property observers to an inherited property. 430 | This enables you to be notified when the value of an inherited property changes, 431 | regardless of how that property was originally implemented. 432 | For more information on property observers, see . 433 | 434 | > Note: You can't add property observers to 435 | > inherited constant stored properties or inherited read-only computed properties. 436 | > The value of these properties can't be set, 437 | > and so it isn't appropriate to provide a `willSet` or `didSet` implementation 438 | > as part of an override. 439 | > 440 | > Note also that you can't provide both 441 | > an overriding setter and an overriding property observer for the same property. 442 | > If you want to observe changes to a property's value, 443 | > and you are already providing a custom setter for that property, 444 | > you can simply observe any value changes from within the custom setter. 445 | 446 | The following example defines a new class called `AutomaticCar`, 447 | which is a subclass of `Car`. 448 | The `AutomaticCar` class represents a car with an automatic gearbox, 449 | which automatically selects an appropriate gear to use based on the current speed: 450 | 451 | ```swift 452 | class AutomaticCar: Car { 453 | override var currentSpeed: Double { 454 | didSet { 455 | gear = Int(currentSpeed / 10.0) + 1 456 | } 457 | } 458 | } 459 | ``` 460 | 461 | 474 | 475 | Whenever you set the `currentSpeed` property of an `AutomaticCar` instance, 476 | the property's `didSet` observer sets the instance's `gear` property to 477 | an appropriate choice of gear for the new speed. 478 | Specifically, the property observer chooses a gear that's 479 | the new `currentSpeed` value divided by `10`, 480 | rounded down to the nearest integer, plus `1`. 481 | A speed of `35.0` produces a gear of `4`: 482 | 483 | ```swift 484 | let automatic = AutomaticCar() 485 | automatic.currentSpeed = 35.0 486 | print("AutomaticCar: \(automatic.description)") 487 | // AutomaticCar: traveling at 35.0 miles per hour in gear 4 488 | ``` 489 | 490 | 500 | 501 | ## Preventing Overrides 502 | 503 | You can prevent a method, property, or subscript from being overridden 504 | by marking it as *final*. 505 | Do this by writing the `final` modifier before 506 | the method, property, or subscript's introducer keyword 507 | (such as `final var`, `final func`, `final class func`, and `final subscript`). 508 | 509 | Any attempt to override a final method, property, or subscript in a subclass 510 | is reported as a compile-time error. 511 | Methods, properties, or subscripts that you add to a class in an extension 512 | can also be marked as final within the extension's definition. 513 | For more information, see . 514 | 515 | 548 | 549 | You can mark an entire class as final by writing the `final` modifier 550 | before the `class` keyword in its class definition (`final class`). 551 | Any attempt to subclass a final class is reported as a compile-time error. 552 | 553 | 589 | 590 | 593 | 594 | 601 | 602 | 608 | 609 | 618 | -------------------------------------------------------------------------------- /TSPL.docc/LanguageGuide/NestedTypes.md: -------------------------------------------------------------------------------- 1 | # Nested Types 2 | 3 | Define types inside the scope of another type. 4 | 5 | Enumerations are often created to support a specific class or structure's functionality. 6 | Similarly, it can be convenient to define utility structures 7 | purely for use within the context of a more complex type, 8 | and protocols that are normally used in conjunction with a specific type. 9 | To accomplish this, Swift enables you to define *nested types*, 10 | whereby you nest supporting types like enumerations, structures, and protocols 11 | within the definition of the type they support. 12 | 13 | To nest a type within another type, 14 | write its definition within the outer braces of the type it supports. 15 | Types can be nested to as many levels as are required. 16 | 17 | ## Nested Types in Action 18 | 19 | The example below defines a structure called `BlackjackCard`, 20 | which models a playing card as used in the game of Blackjack. 21 | The `BlackjackCard` structure contains two nested enumeration types 22 | called `Suit` and `Rank`. 23 | 24 | In Blackjack, the Ace cards have a value of either one or eleven. 25 | This feature is represented by a structure called `Values`, 26 | which is nested within the `Rank` enumeration: 27 | 28 | ```swift 29 | struct BlackjackCard { 30 | 31 | // nested Suit enumeration 32 | enum Suit: Character { 33 | case spades = "♠", hearts = "♡", diamonds = "♢", clubs = "♣" 34 | } 35 | 36 | // nested Rank enumeration 37 | enum Rank: Int { 38 | case two = 2, three, four, five, six, seven, eight, nine, ten 39 | case jack, queen, king, ace 40 | struct Values { 41 | let first: Int, second: Int? 42 | } 43 | var values: Values { 44 | switch self { 45 | case .ace: 46 | return Values(first: 1, second: 11) 47 | case .jack, .queen, .king: 48 | return Values(first: 10, second: nil) 49 | default: 50 | return Values(first: self.rawValue, second: nil) 51 | } 52 | } 53 | } 54 | 55 | // BlackjackCard properties and methods 56 | let rank: Rank, suit: Suit 57 | var description: String { 58 | var output = "suit is \(suit.rawValue)," 59 | output += " value is \(rank.values.first)" 60 | if let second = rank.values.second { 61 | output += " or \(second)" 62 | } 63 | return output 64 | } 65 | } 66 | ``` 67 | 68 | 111 | 112 | The `Suit` enumeration describes the four common playing card suits, 113 | together with a raw `Character` value to represent their symbol. 114 | 115 | The `Rank` enumeration describes the thirteen possible playing card ranks, 116 | together with a raw `Int` value to represent their face value. 117 | (This raw `Int` value isn't used for the Jack, Queen, King, and Ace cards.) 118 | 119 | As mentioned above, the `Rank` enumeration defines 120 | a further nested structure of its own, called `Values`. 121 | This structure encapsulates the fact that most cards have one value, 122 | but the Ace card has two values. 123 | The `Values` structure defines two properties to represent this: 124 | 125 | - `first`, of type `Int` 126 | - `second`, of type `Int?`, or “optional `Int`” 127 | 128 | `Rank` also defines a computed property, `values`, 129 | which returns an instance of the `Values` structure. 130 | This computed property considers the rank of the card 131 | and initializes a new `Values` instance with appropriate values based on its rank. 132 | It uses special values for `jack`, `queen`, `king`, and `ace`. 133 | For the numeric cards, it uses the rank's raw `Int` value. 134 | 135 | The `BlackjackCard` structure itself has two properties --- `rank` and `suit`. 136 | It also defines a computed property called `description`, 137 | which uses the values stored in `rank` and `suit` to build 138 | a description of the name and value of the card. 139 | The `description` property uses optional binding to check whether there's 140 | a second value to display, and if so, 141 | inserts additional description detail for that second value. 142 | 143 | Because `BlackjackCard` is a structure with no custom initializers, 144 | it has an implicit memberwise initializer, 145 | as described in . 146 | You can use this initializer to initialize a new constant called `theAceOfSpades`: 147 | 148 | ```swift 149 | let theAceOfSpades = BlackjackCard(rank: .ace, suit: .spades) 150 | print("theAceOfSpades: \(theAceOfSpades.description)") 151 | // Prints "theAceOfSpades: suit is ♠, value is 1 or 11" 152 | ``` 153 | 154 | 163 | 164 | Even though `Rank` and `Suit` are nested within `BlackjackCard`, 165 | their type can be inferred from context, 166 | and so the initialization of this instance is able to refer to the enumeration cases 167 | by their case names (`.ace` and `.spades`) alone. 168 | In the example above, the `description` property correctly reports that 169 | the Ace of Spades has a value of `1` or `11`. 170 | 171 | ## Referring to Nested Types 172 | 173 | To use a nested type outside of its definition context, 174 | prefix its name with the name of the type it's nested within: 175 | 176 | ```swift 177 | let heartsSymbol = BlackjackCard.Suit.hearts.rawValue 178 | // heartsSymbol is "♡" 179 | ``` 180 | 181 | 190 | 191 | For the example above, 192 | this enables the names of `Suit`, `Rank`, and `Values` to be kept deliberately short, 193 | because their names are naturally qualified by the context in which they're defined. 194 | 195 | 204 | -------------------------------------------------------------------------------- /TSPL.docc/LanguageGuide/Subscripts.md: -------------------------------------------------------------------------------- 1 | # Subscripts 2 | 3 | Access the elements of a collection. 4 | 5 | Classes, structures, and enumerations can define *subscripts*, 6 | which are shortcuts for accessing the member elements of a collection, list, or sequence. 7 | You use subscripts to set and retrieve values by index without needing 8 | separate methods for setting and retrieval. 9 | For example, you access elements in an `Array` instance as `someArray[index]` 10 | and elements in a `Dictionary` instance as `someDictionary[key]`. 11 | 12 | You can define multiple subscripts for a single type, 13 | and the appropriate subscript overload to use is selected 14 | based on the type of index value you pass to the subscript. 15 | Subscripts aren't limited to a single dimension, 16 | and you can define subscripts with multiple input parameters 17 | to suit your custom type's needs. 18 | 19 | 23 | 24 | ## Subscript Syntax 25 | 26 | Subscripts enable you to query instances of a type 27 | by writing one or more values in square brackets after the instance name. 28 | Their syntax is similar to both instance method syntax and computed property syntax. 29 | You write subscript definitions with the `subscript` keyword, 30 | and specify one or more input parameters and a return type, 31 | in the same way as instance methods. 32 | Unlike instance methods, subscripts can be read-write or read-only. 33 | This behavior is communicated by a getter and setter 34 | in the same way as for computed properties: 35 | 36 | ```swift 37 | subscript(index: Int) -> Int { 38 | get { 39 | // Return an appropriate subscript value here. 40 | } 41 | set(newValue) { 42 | // Perform a suitable setting action here. 43 | } 44 | } 45 | ``` 46 | 47 | 64 | 65 | The type of `newValue` is the same as the return value of the subscript. 66 | As with computed properties, you can choose not to specify 67 | the setter's `(newValue)` parameter. 68 | A default parameter called `newValue` is provided to your setter 69 | if you don't provide one yourself. 70 | 71 | As with read-only computed properties, 72 | you can simplify the declaration of a read-only subscript 73 | by removing the `get` keyword and its braces: 74 | 75 | ```swift 76 | subscript(index: Int) -> Int { 77 | // Return an appropriate subscript value here. 78 | } 79 | ``` 80 | 81 | 93 | 94 | Here's an example of a read-only subscript implementation, 95 | which defines a `TimesTable` structure to represent an *n*-times-table of integers: 96 | 97 | ```swift 98 | struct TimesTable { 99 | let multiplier: Int 100 | subscript(index: Int) -> Int { 101 | return multiplier * index 102 | } 103 | } 104 | let threeTimesTable = TimesTable(multiplier: 3) 105 | print("six times three is \(threeTimesTable[6])") 106 | // Prints "six times three is 18" 107 | ``` 108 | 109 | 124 | 125 | In this example, a new instance of `TimesTable` is created 126 | to represent the three-times-table. 127 | This is indicated by passing a value of `3` to the structure's `initializer` 128 | as the value to use for the instance's `multiplier` parameter. 129 | 130 | You can query the `threeTimesTable` instance by calling its subscript, 131 | as shown in the call to `threeTimesTable[6]`. 132 | This requests the sixth entry in the three-times-table, 133 | which returns a value of `18`, or `3` times `6`. 134 | 135 | > Note: An *n*-times-table is based on a fixed mathematical rule. 136 | > It isn't appropriate to set `threeTimesTable[someIndex]` to a new value, 137 | > and so the subscript for `TimesTable` is defined as a read-only subscript. 138 | 139 | ## Subscript Usage 140 | 141 | The exact meaning of “subscript” depends on the context in which it's used. 142 | Subscripts are typically used as a shortcut for accessing 143 | the member elements in a collection, list, or sequence. 144 | You are free to implement subscripts in the most appropriate way for 145 | your particular class or structure's functionality. 146 | 147 | For example, Swift's `Dictionary` type implements a subscript 148 | to set and retrieve the values stored in a `Dictionary` instance. 149 | You can set a value in a dictionary 150 | by providing a key of the dictionary's key type within subscript brackets, 151 | and assigning a value of the dictionary's value type to the subscript: 152 | 153 | ```swift 154 | var numberOfLegs = ["spider": 8, "ant": 6, "cat": 4] 155 | numberOfLegs["bird"] = 2 156 | ``` 157 | 158 | 166 | 167 | The example above defines a variable called `numberOfLegs` 168 | and initializes it with a dictionary literal containing three key-value pairs. 169 | The type of the `numberOfLegs` dictionary is inferred to be `[String: Int]`. 170 | After creating the dictionary, 171 | this example uses subscript assignment to add 172 | a `String` key of `"bird"` and an `Int` value of `2` to the dictionary. 173 | 174 | For more information about `Dictionary` subscripting, 175 | see . 176 | 177 | > Note: Swift's `Dictionary` type implements its key-value subscripting 178 | > as a subscript that takes and returns an *optional* type. 179 | > For the `numberOfLegs` dictionary above, 180 | > the key-value subscript takes and returns a value of type `Int?`, 181 | > or “optional int”. 182 | > The `Dictionary` type uses an optional subscript type to model the fact that 183 | > not every key will have a value, and to give a way to delete a value for a key 184 | > by assigning a `nil` value for that key. 185 | 186 | ## Subscript Options 187 | 188 | Subscripts can take any number of input parameters, 189 | and these input parameters can be of any type. 190 | Subscripts can also return a value of any type. 191 | 192 | Like functions, 193 | subscripts can take a varying number of parameters 194 | and provide default values for their parameters, 195 | as discussed in 196 | and . 197 | However, unlike functions, 198 | subscripts can't use in-out parameters. 199 | 200 | 214 | 215 | A class or structure can provide as many subscript implementations as it needs, 216 | and the appropriate subscript to be used will be inferred based on 217 | the types of the value or values that are contained within the subscript brackets 218 | at the point that the subscript is used. 219 | This definition of multiple subscripts is known as *subscript overloading*. 220 | 221 | While it's most common for a subscript to take a single parameter, 222 | you can also define a subscript with multiple parameters 223 | if it's appropriate for your type. 224 | The following example defines a `Matrix` structure, 225 | which represents a two-dimensional matrix of `Double` values. 226 | The `Matrix` structure's subscript takes two integer parameters: 227 | 228 | ```swift 229 | struct Matrix { 230 | let rows: Int, columns: Int 231 | var grid: [Double] 232 | init(rows: Int, columns: Int) { 233 | self.rows = rows 234 | self.columns = columns 235 | grid = Array(repeating: 0.0, count: rows * columns) 236 | } 237 | func indexIsValid(row: Int, column: Int) -> Bool { 238 | return row >= 0 && row < rows && column >= 0 && column < columns 239 | } 240 | subscript(row: Int, column: Int) -> Double { 241 | get { 242 | assert(indexIsValid(row: row, column: column), "Index out of range") 243 | return grid[(row * columns) + column] 244 | } 245 | set { 246 | assert(indexIsValid(row: row, column: column), "Index out of range") 247 | grid[(row * columns) + column] = newValue 248 | } 249 | } 250 | } 251 | ``` 252 | 253 | 281 | 282 | `Matrix` provides an initializer that takes two parameters called `rows` and `columns`, 283 | and creates an array that's large enough to store `rows * columns` values of type `Double`. 284 | Each position in the matrix is given an initial value of `0.0`. 285 | To achieve this, the array's size, and an initial cell value of `0.0`, 286 | are passed to an array initializer that creates and initializes a new array of the correct size. 287 | This initializer is described in more detail 288 | in . 289 | 290 | You can construct a new `Matrix` instance by passing 291 | an appropriate row and column count to its initializer: 292 | 293 | ```swift 294 | var matrix = Matrix(rows: 2, columns: 2) 295 | ``` 296 | 297 | 305 | 306 | The example above creates a new `Matrix` instance with two rows and two columns. 307 | The `grid` array for this `Matrix` instance 308 | is effectively a flattened version of the matrix, 309 | as read from top left to bottom right: 310 | 311 | ![](subscriptMatrix01) 312 | 313 | Values in the matrix can be set by passing row and column values into the subscript, 314 | separated by a comma: 315 | 316 | ```swift 317 | matrix[0, 1] = 1.5 318 | matrix[1, 0] = 3.2 319 | ``` 320 | 321 | 333 | 334 | These two statements call the subscript's setter to set 335 | a value of `1.5` in the top right position of the matrix 336 | (where `row` is `0` and `column` is `1`), 337 | and `3.2` in the bottom left position 338 | (where `row` is `1` and `column` is `0`): 339 | 340 | ![](subscriptMatrix02) 341 | 342 | The `Matrix` subscript's getter and setter both contain an assertion 343 | to check that the subscript's `row` and `column` values are valid. 344 | To assist with these assertions, 345 | `Matrix` includes a convenience method called `indexIsValid(row:column:)`, 346 | which checks whether the requested `row` and `column` 347 | are inside the bounds of the matrix: 348 | 349 | ```swift 350 | func indexIsValid(row: Int, column: Int) -> Bool { 351 | return row >= 0 && row < rows && column >= 0 && column < columns 352 | } 353 | ``` 354 | 355 | 366 | 367 | An assertion is triggered if you try to access a subscript 368 | that's outside of the matrix bounds: 369 | 370 | ```swift 371 | let someValue = matrix[2, 2] 372 | // This triggers an assert, because [2, 2] is outside of the matrix bounds. 373 | ``` 374 | 375 | 384 | 385 | ## Type Subscripts 386 | 387 | Instance subscripts, as described above, 388 | are subscripts that you call on an instance of a particular type. 389 | You can also define subscripts that are called on the type itself. 390 | This kind of subscript is called a *type subscript*. 391 | You indicate a type subscript 392 | by writing the `static` keyword before the `subscript` keyword. 393 | Classes can use the `class` keyword instead, 394 | to allow subclasses to override the superclass’s implementation of that subscript. 395 | The example below shows how you define and call a type subscript: 396 | 397 | ```swift 398 | enum Planet: Int { 399 | case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune 400 | static subscript(n: Int) -> Planet { 401 | return Planet(rawValue: n)! 402 | } 403 | } 404 | let mars = Planet[4] 405 | print(mars) 406 | ``` 407 | 408 | 424 | 425 | 434 | -------------------------------------------------------------------------------- /TSPL.docc/LanguageGuide/TypeCasting.md: -------------------------------------------------------------------------------- 1 | # Type Casting 2 | 3 | Determine a value's runtime type and give it more specific type information. 4 | 5 | *Type casting* is a way to check the type of an instance, 6 | or to treat that instance as a different 7 | superclass or subclass from somewhere else in its own class hierarchy. 8 | 9 | Type casting in Swift is implemented with the `is` and `as` operators. 10 | These two operators provide a simple and expressive way 11 | to check the type of a value or cast a value to a different type. 12 | 13 | You can also use type casting to check whether a type conforms to a protocol, 14 | as described in . 15 | 16 | ## Defining a Class Hierarchy for Type Casting 17 | 18 | You can use type casting with a hierarchy of classes and subclasses 19 | to check the type of a particular class instance 20 | and to cast that instance to another class within the same hierarchy. 21 | The three code snippets below define a hierarchy of classes 22 | and an array containing instances of those classes, 23 | for use in an example of type casting. 24 | 25 | The first snippet defines a new base class called `MediaItem`. 26 | This class provides basic functionality for any kind of item that appears 27 | in a digital media library. 28 | Specifically, it declares a `name` property of type `String`, 29 | and an `init(name:)` initializer. 30 | (It's assumed that all media items, including all movies and songs, will have a name.) 31 | 32 | ```swift 33 | class MediaItem { 34 | var name: String 35 | init(name: String) { 36 | self.name = name 37 | } 38 | } 39 | ``` 40 | 41 | 53 | 54 | The next snippet defines two subclasses of `MediaItem`. 55 | The first subclass, `Movie`, encapsulates additional information about a movie or film. 56 | It adds a `director` property on top of the base `MediaItem` class, 57 | with a corresponding initializer. 58 | The second subclass, `Song`, adds an `artist` property and initializer 59 | on top of the base class: 60 | 61 | ```swift 62 | class Movie: MediaItem { 63 | var director: String 64 | init(name: String, director: String) { 65 | self.director = director 66 | super.init(name: name) 67 | } 68 | } 69 | 70 | class Song: MediaItem { 71 | var artist: String 72 | init(name: String, artist: String) { 73 | self.artist = artist 74 | super.init(name: name) 75 | } 76 | } 77 | ``` 78 | 79 | 100 | 101 | The final snippet creates a constant array called `library`, 102 | which contains two `Movie` instances and three `Song` instances. 103 | The type of the `library` array is inferred 104 | by initializing it with the contents of an array literal. 105 | Swift's type checker is able to deduce that `Movie` and `Song` have 106 | a common superclass of `MediaItem`, 107 | and so it infers a type of `[MediaItem]` for the `library` array: 108 | 109 | ```swift 110 | let library = [ 111 | Movie(name: "Casablanca", director: "Michael Curtiz"), 112 | Song(name: "Blue Suede Shoes", artist: "Elvis Presley"), 113 | Movie(name: "Citizen Kane", director: "Orson Welles"), 114 | Song(name: "The One And Only", artist: "Chesney Hawkes"), 115 | Song(name: "Never Gonna Give You Up", artist: "Rick Astley") 116 | ] 117 | // the type of "library" is inferred to be [MediaItem] 118 | ``` 119 | 120 | 136 | 137 | The items stored in `library` are still `Movie` and `Song` instances behind the scenes. 138 | However, if you iterate over the contents of this array, 139 | the items you receive back are typed as `MediaItem`, 140 | and not as `Movie` or `Song`. 141 | In order to work with them as their native type, 142 | you need to *check* their type, 143 | or *downcast* them to a different type, 144 | as described below. 145 | 146 | ## Checking Type 147 | 148 | Use the *type check operator* (`is`) to check 149 | whether an instance is of a certain subclass type. 150 | The type check operator returns `true` if the instance is of that subclass type 151 | and `false` if it's not. 152 | 153 | The example below defines two variables, `movieCount` and `songCount`, 154 | which count the number of `Movie` and `Song` instances in the `library` array: 155 | 156 | ```swift 157 | var movieCount = 0 158 | var songCount = 0 159 | 160 | for item in library { 161 | if item is Movie { 162 | movieCount += 1 163 | } else if item is Song { 164 | songCount += 1 165 | } 166 | } 167 | 168 | print("Media library contains \(movieCount) movies and \(songCount) songs") 169 | // Prints "Media library contains 2 movies and 3 songs" 170 | ``` 171 | 172 | 191 | 192 | This example iterates through all items in the `library` array. 193 | On each pass, the `for`-`in` loop sets the `item` constant 194 | to the next `MediaItem` in the array. 195 | 196 | `item is Movie` returns `true` if the current `MediaItem` 197 | is a `Movie` instance and `false` if it's not. 198 | Similarly, `item is Song` checks whether the item is a `Song` instance. 199 | At the end of the `for`-`in` loop, the values of `movieCount` and `songCount` 200 | contain a count of how many `MediaItem` instances were found of each type. 201 | 202 | ## Downcasting 203 | 204 | A constant or variable of a certain class type may actually refer to 205 | an instance of a subclass behind the scenes. 206 | Where you believe this is the case, 207 | you can try to *downcast* to the subclass type 208 | with a *type cast operator* (`as?` or `as!`). 209 | 210 | Because downcasting can fail, 211 | the type cast operator comes in two different forms. 212 | The conditional form, `as?`, returns an optional value of the type you are trying to downcast to. 213 | The forced form, `as!`, attempts the downcast and force-unwraps the result 214 | as a single compound action. 215 | 216 | Use the conditional form of the type cast operator (`as?`) 217 | when you aren't sure if the downcast will succeed. 218 | This form of the operator will always return an optional value, 219 | and the value will be `nil` if the downcast was not possible. 220 | This enables you to check for a successful downcast. 221 | 222 | Use the forced form of the type cast operator (`as!`) 223 | only when you are sure that the downcast will always succeed. 224 | This form of the operator will trigger a runtime error 225 | if you try to downcast to an incorrect class type. 226 | 227 | The example below iterates over each `MediaItem` in `library`, 228 | and prints an appropriate description for each item. 229 | To do this, it needs to access each item as a true `Movie` or `Song`, 230 | and not just as a `MediaItem`. 231 | This is necessary in order for it to be able to access 232 | the `director` or `artist` property of a `Movie` or `Song` 233 | for use in the description. 234 | 235 | In this example, each item in the array might be a `Movie`, 236 | or it might be a `Song`. 237 | You don't know in advance which actual class to use for each item, 238 | and so it's appropriate to use the conditional form of the type cast operator (`as?`) 239 | to check the downcast each time through the loop: 240 | 241 | ```swift 242 | for item in library { 243 | if let movie = item as? Movie { 244 | print("Movie: \(movie.name), dir. \(movie.director)") 245 | } else if let song = item as? Song { 246 | print("Song: \(song.name), by \(song.artist)") 247 | } 248 | } 249 | 250 | // Movie: Casablanca, dir. Michael Curtiz 251 | // Song: Blue Suede Shoes, by Elvis Presley 252 | // Movie: Citizen Kane, dir. Orson Welles 253 | // Song: The One And Only, by Chesney Hawkes 254 | // Song: Never Gonna Give You Up, by Rick Astley 255 | ``` 256 | 257 | 276 | 277 | The example starts by trying to downcast the current `item` as a `Movie`. 278 | Because `item` is a `MediaItem` instance, it's possible that it *might* be a `Movie`; 279 | equally, it's also possible that it might be a `Song`, 280 | or even just a base `MediaItem`. 281 | Because of this uncertainty, the `as?` form of the type cast operator returns an *optional* value 282 | when attempting to downcast to a subclass type. 283 | The result of `item as? Movie` is of type `Movie?`, or “optional `Movie`”. 284 | 285 | Downcasting to `Movie` fails when applied to 286 | the `Song` instances in the library array. 287 | To cope with this, the example above uses optional binding 288 | to check whether the optional `Movie` actually contains a value 289 | (that is, to find out whether the downcast succeeded.) 290 | This optional binding is written “`if let movie = item as? Movie`”, 291 | which can be read as: 292 | 293 | “Try to access `item` as a `Movie`. 294 | If this is successful, 295 | set a new temporary constant called `movie` to 296 | the value stored in the returned optional `Movie`.” 297 | 298 | If the downcasting succeeds, the properties of `movie` are then used 299 | to print a description for that `Movie` instance, including the name of its `director`. 300 | A similar principle is used to check for `Song` instances, 301 | and to print an appropriate description (including `artist` name) 302 | whenever a `Song` is found in the library. 303 | 304 | > Note: Casting doesn't actually modify the instance or change its values. 305 | > The underlying instance remains the same; it's simply treated and accessed 306 | > as an instance of the type to which it has been cast. 307 | 308 | 313 | 314 | 319 | 320 | ## Type Casting for Any and AnyObject 321 | 322 | Swift provides two special types for working with nonspecific types: 323 | 324 | - `Any` can represent an instance of any type at all, including function types. 325 | - `AnyObject` can represent an instance of any class type. 326 | 327 | Use `Any` and `AnyObject` only when you explicitly need 328 | the behavior and capabilities they provide. 329 | It's always better to be specific about the types you expect to work with in your code. 330 | 331 | Here's an example of using `Any` to work with a mix of different types, 332 | including function types and nonclass types. 333 | The example creates an array called `things`, which can store values of type `Any`: 334 | 335 | ```swift 336 | var things: [Any] = [] 337 | 338 | things.append(0) 339 | things.append(0.0) 340 | things.append(42) 341 | things.append(3.14159) 342 | things.append("hello") 343 | things.append((3.0, 5.0)) 344 | things.append(Movie(name: "Ghostbusters", director: "Ivan Reitman")) 345 | things.append({ (name: String) -> String in "Hello, \(name)" }) 346 | ``` 347 | 348 | 364 | 365 | The `things` array contains 366 | two `Int` values, two `Double` values, a `String` value, 367 | a tuple of type `(Double, Double)`, 368 | the movie “Ghostbusters”, 369 | and a closure expression that takes a `String` value 370 | and returns another `String` value. 371 | 372 | To discover the specific type of a constant or variable 373 | that's known only to be of type `Any` or `AnyObject`, 374 | you can use an `is` or `as` pattern in a `switch` statement's cases. 375 | The example below iterates over the items in the `things` array 376 | and queries the type of each item with a `switch` statement. 377 | Several of the `switch` statement's cases bind their matched value to 378 | a constant of the specified type to enable its value to be printed: 379 | 380 | ```swift 381 | for thing in things { 382 | switch thing { 383 | case 0 as Int: 384 | print("zero as an Int") 385 | case 0 as Double: 386 | print("zero as a Double") 387 | case let someInt as Int: 388 | print("an integer value of \(someInt)") 389 | case let someDouble as Double where someDouble > 0: 390 | print("a positive double value of \(someDouble)") 391 | case is Double: 392 | print("some other double value that I don't want to print") 393 | case let someString as String: 394 | print("a string value of \"\(someString)\"") 395 | case let (x, y) as (Double, Double): 396 | print("an (x, y) point at \(x), \(y)") 397 | case let movie as Movie: 398 | print("a movie called \(movie.name), dir. \(movie.director)") 399 | case let stringConverter as (String) -> String: 400 | print(stringConverter("Michael")) 401 | default: 402 | print("something else") 403 | } 404 | } 405 | 406 | // zero as an Int 407 | // zero as a Double 408 | // an integer value of 42 409 | // a positive double value of 3.14159 410 | // a string value of "hello" 411 | // an (x, y) point at 3.0, 5.0 412 | // a movie called Ghostbusters, dir. Ivan Reitman 413 | // Hello, Michael 414 | ``` 415 | 416 | 455 | 456 | > Note: The `Any` type represents values of any type, including optional types. 457 | > Swift gives you a warning if you use an optional value 458 | > where a value of type `Any` is expected. 459 | > If you really do need to use an optional value as an `Any` value, 460 | > you can use the `as` operator to explicitly cast the optional to `Any`, 461 | > as shown below. 462 | > 463 | > ```swift 464 | > let optionalNumber: Int? = 3 465 | > things.append(optionalNumber) // Warning 466 | > things.append(optionalNumber as Any) // No warning 467 | > ``` 468 | 469 | 493 | 494 | 524 | 525 | 534 | -------------------------------------------------------------------------------- /TSPL.docc/ReferenceManual/AboutTheLanguageReference.md: -------------------------------------------------------------------------------- 1 | # About the Language Reference 2 | 3 | Read the notation that the formal grammar uses. 4 | 5 | This part of the book describes the formal grammar of the Swift programming language. 6 | The grammar described here is intended to help you understand the language in more 7 | detail, rather than to allow you to directly implement a parser or compiler. 8 | 9 | The Swift language is relatively small, because many common types, functions, and operators 10 | that appear virtually everywhere in Swift code 11 | are actually defined in the Swift standard library. Although these types, functions, 12 | and operators aren't part of the Swift language itself, 13 | they're used extensively in the discussions and code examples in this part of the book. 14 | 15 | ## How to Read the Grammar 16 | 17 | The notation used to describe the formal grammar of the Swift programming language 18 | follows a few conventions: 19 | 20 | - An arrow (→) is used to mark grammar productions and can be read as "can consist of." 21 | - Syntactic categories are indicated by *italic* text and appear on both sides 22 | of a grammar production rule. 23 | - Literal words and punctuation are indicated by **`boldface constant width`** text 24 | and appear only on the right-hand side of a grammar production rule. 25 | - Alternative grammar productions are separated by vertical 26 | bars (|). When alternative productions are too long to read easily, 27 | they're broken into multiple grammar production rules on new lines. 28 | - In a few cases, regular font text is used to describe the right-hand side 29 | of a grammar production rule. 30 | - Optional syntactic categories and literals are marked by a trailing 31 | question mark, *?*. 32 | 33 | As an example, the grammar of a getter-setter block is defined as follows: 34 | 35 | > Grammar of a getter-setter block: 36 | > 37 | > *getter-setter-block* → **`{`** *getter-clause* *setter-clause*_?_ **`}`** | **`{`** *setter-clause* *getter-clause* **`}`** 38 | 39 | This definition indicates that a getter-setter block can consist of a getter clause 40 | followed by an optional setter clause, enclosed in braces, 41 | *or* a setter clause followed by a getter clause, enclosed in braces. 42 | The grammar production above is equivalent to the following two productions, 43 | where the alternatives are spelled out explicitly: 44 | 45 | > Grammar of a getter-setter block: 46 | > 47 | > 48 | > *getter-setter-block* → **`{`** *getter-clause* *setter-clause*_?_ **`}`** \ 49 | > *getter-setter-block* → **`{`** *setter-clause* *getter-clause* **`}`** 50 | 51 | 60 | -------------------------------------------------------------------------------- /TSPL.docc/ReferenceManual/GenericParametersAndArguments.md: -------------------------------------------------------------------------------- 1 | # Generic Parameters and Arguments 2 | 3 | Generalize declarations to abstract away concrete types. 4 | 5 | This chapter describes parameters and arguments for generic types, functions, and 6 | initializers. When you declare a generic type, function, subscript, or initializer, 7 | you specify the type parameters that the generic type, function, or initializer 8 | can work with. These type parameters act as placeholders that 9 | are replaced by actual concrete type arguments when an instance of a generic type is 10 | created or a generic function or initializer is called. 11 | 12 | For an overview of generics in Swift, see . 13 | 14 | 18 | 19 | ## Generic Parameter Clause 20 | 21 | A *generic parameter clause* specifies the type parameters of a generic 22 | type or function, along with any associated constraints and requirements on those parameters. 23 | A generic parameter clause is enclosed in angle brackets (<>) 24 | and has the following form: 25 | 26 | ```swift 27 | <<#generic parameter list#>> 28 | ``` 29 | 30 | The *generic parameter list* is a comma-separated list of generic parameters, 31 | each of which has the following form: 32 | 33 | ```swift 34 | <#type parameter#>: <#constraint#> 35 | ``` 36 | 37 | A generic parameter consists of a *type parameter* followed by 38 | an optional *constraint*. A *type parameter* is simply the name 39 | of a placeholder type 40 | (for example, `T`, `U`, `V`, `Key`, `Value`, and so on). 41 | You have access to the type parameters (and any of their associated types) in the rest of the 42 | type, function, or initializer declaration, including in the signature of the function 43 | or initializer. 44 | 45 | The *constraint* specifies that a type parameter inherits 46 | from a specific class or conforms to a protocol or protocol composition. 47 | For example, in the generic function below, the generic parameter `T: Comparable` 48 | indicates that any type argument substituted 49 | for the type parameter `T` must conform to the `Comparable` protocol. 50 | 51 | ```swift 52 | func simpleMax(_ x: T, _ y: T) -> T { 53 | if x < y { 54 | return y 55 | } 56 | return x 57 | } 58 | ``` 59 | 60 | 72 | 73 | Because `Int` and `Double`, for example, both conform to the `Comparable` protocol, 74 | this function accepts arguments of either type. In contrast with generic types, you don't 75 | specify a generic argument clause when you use a generic function or initializer. 76 | The type arguments are instead inferred from the type of the arguments passed 77 | to the function or initializer. 78 | 79 | ```swift 80 | simpleMax(17, 42) // T is inferred to be Int 81 | simpleMax(3.14159, 2.71828) // T is inferred to be Double 82 | ``` 83 | 84 | 96 | 97 | 101 | 102 | ### Generic Where Clauses 103 | 104 | You can specify additional requirements on type parameters and their associated types 105 | by including a generic `where` clause right before the opening curly brace 106 | of a type or function's body. 107 | A generic `where` clause consists of the `where` keyword, 108 | followed by a comma-separated list of one or more *requirements*. 109 | 110 | ```swift 111 | where <#requirements#> 112 | ``` 113 | 114 | The *requirements* in a generic `where` clause specify that a type parameter inherits from 115 | a class or conforms to a protocol or protocol composition. 116 | Although the generic `where` clause provides syntactic 117 | sugar for expressing simple constraints on type parameters 118 | (for example, `` is equivalent to ` where T: Comparable` and so on), 119 | you can use it to provide more complex constraints on type parameters 120 | and their associated types. For example, 121 | you can constrain the associated types of type parameters to conform to protocols. 122 | For example, ` where S.Iterator.Element: Equatable` 123 | specifies that `S` conforms to the `Sequence` protocol 124 | and that the associated type `S.Iterator.Element` 125 | conforms to the `Equatable` protocol. 126 | This constraint ensures that each element of the sequence is equatable. 127 | 128 | You can also specify the requirement that two types be identical, 129 | using the `==` operator. For example, 130 | ` where S1.Iterator.Element == S2.Iterator.Element` 131 | expresses the constraints that `S1` and `S2` conform to the `Sequence` protocol 132 | and that the elements of both sequences must be of the same type. 133 | 134 | Any type argument substituted for a type parameter must 135 | meet all the constraints and requirements placed on the type parameter. 136 | 137 | A generic `where` clause can appear 138 | as part of a declaration that includes type parameters, 139 | or as part of a declaration 140 | that's nested inside of a declaration that includes type parameters. 141 | The generic `where` clause for a nested declaration 142 | can still refer to the type parameters of the enclosing declaration; 143 | however, 144 | the requirements from that `where` clause 145 | apply only to the declaration where it's written. 146 | 147 | If the enclosing declaration also has a `where` clause, 148 | the requirements from both clauses are combined. 149 | In the example below, `startsWithZero()` is available 150 | only if `Element` conforms to both `SomeProtocol` and `Numeric`. 151 | 152 | ```swift 153 | extension Collection where Element: SomeProtocol { 154 | func startsWithZero() -> Bool where Element: Numeric { 155 | return first == .zero 156 | } 157 | } 158 | ``` 159 | 160 | 175 | 176 | 196 | 197 | You can overload a generic function or initializer by providing different 198 | constraints, requirements, or both on the type parameters. 199 | When you call an overloaded generic function or initializer, 200 | the compiler uses these constraints to resolve which overloaded function 201 | or initializer to invoke. 202 | 203 | For more information about generic `where` clauses and to see an example 204 | of one in a generic function declaration, 205 | see . 206 | 207 | > Grammar of a generic parameter clause: 208 | > 209 | > *generic-parameter-clause* → **`<`** *generic-parameter-list* **`>`** \ 210 | > *generic-parameter-list* → *generic-parameter* | *generic-parameter* **`,`** *generic-parameter-list* \ 211 | > *generic-parameter* → *type-name* \ 212 | > *generic-parameter* → *type-name* **`:`** *type-identifier* \ 213 | > *generic-parameter* → *type-name* **`:`** *protocol-composition-type* 214 | > 215 | > *generic-where-clause* → **`where`** *requirement-list* \ 216 | > *requirement-list* → *requirement* | *requirement* **`,`** *requirement-list* \ 217 | > *requirement* → *conformance-requirement* | *same-type-requirement* 218 | > 219 | > *conformance-requirement* → *type-identifier* **`:`** *type-identifier* \ 220 | > *conformance-requirement* → *type-identifier* **`:`** *protocol-composition-type* \ 221 | > *same-type-requirement* → *type-identifier* **`==`** *type* 222 | 223 | 228 | 229 | ## Generic Argument Clause 230 | 231 | A *generic argument clause* specifies the type arguments of a generic 232 | type. 233 | A generic argument clause is enclosed in angle brackets (<>) 234 | and has the following form: 235 | 236 | ```swift 237 | <<#generic argument list#>> 238 | ``` 239 | 240 | The *generic argument list* is a comma-separated list of type arguments. 241 | A *type argument* is the name of an actual concrete type that replaces 242 | a corresponding type parameter in the generic parameter clause of a generic type. 243 | The result is a specialized version of that generic type. 244 | The example below shows a simplified version of the Swift standard library's 245 | generic dictionary type. 246 | 247 | ```swift 248 | struct Dictionary: Collection, ExpressibleByDictionaryLiteral { 249 | /* ... */ 250 | } 251 | ``` 252 | 253 | 256 | 257 | The specialized version of the generic `Dictionary` type, `Dictionary` 258 | is formed by replacing the generic parameters `Key: Hashable` and `Value` 259 | with the concrete type arguments `String` and `Int`. Each type argument must satisfy 260 | all the constraints of the generic parameter it replaces, including any additional 261 | requirements specified in a generic `where` clause. In the example above, 262 | the `Key` type parameter is constrained to conform to the `Hashable` protocol 263 | and therefore `String` must also conform to the `Hashable` protocol. 264 | 265 | You can also replace a type parameter with a type argument that's itself 266 | a specialized version of a generic type (provided it satisfies the appropriate 267 | constraints and requirements). For example, you can replace the type parameter 268 | `Element` in `Array` with a specialized version of an array, `Array`, 269 | to form an array whose elements are themselves arrays of integers. 270 | 271 | ```swift 272 | let arrayOfArrays: Array> = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 273 | ``` 274 | 275 | 282 | 283 | As mentioned in , 284 | you don't use a generic argument clause to specify the type arguments 285 | of a generic function or initializer. 286 | 287 | > Grammar of a generic argument clause: 288 | > 289 | > *generic-argument-clause* → **`<`** *generic-argument-list* **`>`** \ 290 | > *generic-argument-list* → *generic-argument* | *generic-argument* **`,`** *generic-argument-list* \ 291 | > *generic-argument* → *type* 292 | 293 | 302 | -------------------------------------------------------------------------------- /TSPL.docc/ReferenceManual/Patterns.md: -------------------------------------------------------------------------------- 1 | # Patterns 2 | 3 | Match and destructure values. 4 | 5 | A *pattern* represents the structure of a single value 6 | or a composite value. 7 | For example, the structure of a tuple `(1, 2)` is a comma-separated list of two 8 | elements. Because patterns represent the structure of a value rather than any 9 | one particular value, you can match them with a variety of values. 10 | For instance, the pattern `(x, y)` matches the tuple `(1, 2)` and any other 11 | two-element tuple. In addition to matching a pattern with a value, 12 | you can extract part or all of a composite value and bind each part 13 | to a constant or variable name. 14 | 15 | In Swift, there are two basic kinds of patterns: 16 | those that successfully match any kind of value, 17 | and those that may fail to match a specified value at runtime. 18 | 19 | The first kind of pattern is used for destructuring values 20 | in simple variable, constant, and optional bindings. 21 | These include wildcard patterns, identifier patterns, 22 | and any value binding or tuple patterns containing 23 | them. You can specify a type annotation for these patterns 24 | to constrain them to match only values of a certain type. 25 | 26 | The second kind of pattern is used for full pattern matching, 27 | where the values you're trying to match against may not be there at runtime. 28 | These include enumeration case patterns, optional patterns, expression patterns, 29 | and type-casting patterns. You use these patterns in a case label of a `switch` 30 | statement, a `catch` clause of a `do` statement, 31 | or in the case condition of an `if`, `while`, 32 | `guard`, or `for`-`in` statement. 33 | 34 | > Grammar of a pattern: 35 | > 36 | > *pattern* → *wildcard-pattern* *type-annotation*_?_ \ 37 | > *pattern* → *identifier-pattern* *type-annotation*_?_ \ 38 | > *pattern* → *value-binding-pattern* \ 39 | > *pattern* → *tuple-pattern* *type-annotation*_?_ \ 40 | > *pattern* → *enum-case-pattern* \ 41 | > *pattern* → *optional-pattern* \ 42 | > *pattern* → *type-casting-pattern* \ 43 | > *pattern* → *expression-pattern* 44 | 45 | ## Wildcard Pattern 46 | 47 | A *wildcard pattern* matches and ignores any value and consists of an underscore 48 | (`_`). Use a wildcard pattern when you don't care about the values being 49 | matched against. For example, the following code iterates through the closed range `1...3`, 50 | ignoring the current value of the range on each iteration of the loop: 51 | 52 | ```swift 53 | for _ in 1...3 { 54 | // Do something three times. 55 | } 56 | ``` 57 | 58 | 67 | 68 | > Grammar of a wildcard pattern: 69 | > 70 | > *wildcard-pattern* → **`_`** 71 | 72 | ## Identifier Pattern 73 | 74 | An *identifier pattern* matches any value and binds the matched value to a 75 | variable or constant name. 76 | For example, in the following constant declaration, `someValue` is an identifier pattern 77 | that matches the value `42` of type `Int`: 78 | 79 | ```swift 80 | let someValue = 42 81 | ``` 82 | 83 | 90 | 91 | When the match succeeds, the value `42` is bound (assigned) 92 | to the constant name `someValue`. 93 | 94 | When the pattern on the left-hand side of a variable or constant declaration 95 | is an identifier pattern, 96 | the identifier pattern is implicitly a subpattern of a value-binding pattern. 97 | 98 | > Grammar of an identifier pattern: 99 | > 100 | > *identifier-pattern* → *identifier* 101 | 102 | ## Value-Binding Pattern 103 | 104 | A *value-binding pattern* binds matched values to variable or constant names. 105 | Value-binding patterns that bind a matched value to the name of a constant 106 | begin with the `let` keyword; those that bind to the name of variable 107 | begin with the `var` keyword. 108 | 109 | Identifiers patterns within a value-binding pattern 110 | bind new named variables or constants to their matching values. For example, 111 | you can decompose the elements of a tuple and bind the value of each element to a 112 | corresponding identifier pattern. 113 | 114 | ```swift 115 | let point = (3, 2) 116 | switch point { 117 | // Bind x and y to the elements of point. 118 | case let (x, y): 119 | print("The point is at (\(x), \(y)).") 120 | } 121 | // Prints "The point is at (3, 2)." 122 | ``` 123 | 124 | 137 | 138 | In the example above, `let` distributes to each identifier pattern in the 139 | tuple pattern `(x, y)`. Because of this behavior, the `switch` cases 140 | `case let (x, y):` and `case (let x, let y):` match the same values. 141 | 142 | > Grammar of a value-binding pattern: 143 | > 144 | > *value-binding-pattern* → **`var`** *pattern* | **`let`** *pattern* 145 | 146 | 153 | 154 | ## Tuple Pattern 155 | 156 | A *tuple pattern* is a comma-separated list of zero or more patterns, enclosed in 157 | parentheses. Tuple patterns match values of corresponding tuple types. 158 | 159 | You can constrain a tuple pattern to match certain kinds of tuple types 160 | by using type annotations. 161 | For example, the tuple pattern `(x, y): (Int, Int)` in the constant declaration 162 | `let (x, y): (Int, Int) = (1, 2)` matches only tuple types in which 163 | both elements are of type `Int`. 164 | 165 | When a tuple pattern is used as the pattern in a `for`-`in` statement 166 | or in a variable or constant declaration, it can contain only wildcard patterns, 167 | identifier patterns, optional patterns, or other tuple patterns that contain those. 168 | For example, 169 | the following code isn't valid because the element `0` in the tuple pattern `(x, 0)` is 170 | an expression pattern: 171 | 172 | ```swift 173 | let points = [(0, 0), (1, 0), (1, 1), (2, 0), (2, 1)] 174 | // This code isn't valid. 175 | for (x, 0) in points { 176 | /* ... */ 177 | } 178 | ``` 179 | 180 | 195 | 196 | The parentheses around a tuple pattern that contains a single element have no effect. 197 | The pattern matches values of that single element's type. For example, the following are 198 | equivalent: 199 | 200 | 205 | 206 | ```swift 207 | let a = 2 // a: Int = 2 208 | let (a) = 2 // a: Int = 2 209 | let (a): Int = 2 // a: Int = 2 210 | ``` 211 | 212 | 233 | 234 | > Grammar of a tuple pattern: 235 | > 236 | > *tuple-pattern* → **`(`** *tuple-pattern-element-list*_?_ **`)`** \ 237 | > *tuple-pattern-element-list* → *tuple-pattern-element* | *tuple-pattern-element* **`,`** *tuple-pattern-element-list* \ 238 | > *tuple-pattern-element* → *pattern* | *identifier* **`:`** *pattern* 239 | 240 | ## Enumeration Case Pattern 241 | 242 | An *enumeration case pattern* matches a case of an existing enumeration type. 243 | Enumeration case patterns appear in `switch` statement 244 | case labels and in the case conditions of `if`, `while`, `guard`, and `for`-`in` 245 | statements. 246 | 247 | If the enumeration case you're trying to match has any associated values, 248 | the corresponding enumeration case pattern must specify a tuple pattern that contains 249 | one element for each associated value. For an example that uses a `switch` statement 250 | to match enumeration cases containing associated values, 251 | see . 252 | 253 | An enumeration case pattern also matches 254 | values of that case wrapped in an optional. 255 | This simplified syntax lets you omit an optional pattern. 256 | Note that, 257 | because `Optional` is implemented as an enumeration, 258 | `.none` and `.some` can appear 259 | in the same switch as the cases of the enumeration type. 260 | 261 | ```swift 262 | enum SomeEnum { case left, right } 263 | let x: SomeEnum? = .left 264 | switch x { 265 | case .left: 266 | print("Turn left") 267 | case .right: 268 | print("Turn right") 269 | case nil: 270 | print("Keep going straight") 271 | } 272 | // Prints "Turn left" 273 | ``` 274 | 275 | 292 | 293 | > Grammar of an enumeration case pattern: 294 | > 295 | > *enum-case-pattern* → *type-identifier*_?_ **`.`** *enum-case-name* *tuple-pattern*_?_ 296 | 297 | ## Optional Pattern 298 | 299 | An *optional pattern* matches values wrapped in a `some(Wrapped)` case 300 | of an `Optional` enumeration. 301 | Optional patterns consist of an identifier pattern followed immediately by a question mark 302 | and appear in the same places as enumeration case patterns. 303 | 304 | Because optional patterns are syntactic sugar for `Optional` 305 | enumeration case patterns, 306 | the following are equivalent: 307 | 308 | ```swift 309 | let someOptional: Int? = 42 310 | // Match using an enumeration case pattern. 311 | if case .some(let x) = someOptional { 312 | print(x) 313 | } 314 | 315 | // Match using an optional pattern. 316 | if case let x? = someOptional { 317 | print(x) 318 | } 319 | ``` 320 | 321 | 339 | 340 | The optional pattern provides a convenient way to 341 | iterate over an array of optional values in a `for`-`in` statement, 342 | executing the body of the loop only for non-`nil` elements. 343 | 344 | ```swift 345 | let arrayOfOptionalInts: [Int?] = [nil, 2, 3, nil, 5] 346 | // Match only non-nil values. 347 | for case let number? in arrayOfOptionalInts { 348 | print("Found a \(number)") 349 | } 350 | // Found a 2 351 | // Found a 3 352 | // Found a 5 353 | ``` 354 | 355 | 369 | 370 | > Grammar of an optional pattern: 371 | > 372 | > *optional-pattern* → *identifier-pattern* **`?`** 373 | 374 | ## Type-Casting Patterns 375 | 376 | There are two type-casting patterns, the `is` pattern and the `as` pattern. 377 | The `is` pattern appears only in `switch` statement 378 | case labels. The `is` and `as` patterns have the following form: 379 | 380 | ```swift 381 | is <#type#> 382 | <#pattern#> as <#type#> 383 | ``` 384 | 385 | The `is` pattern matches a value if the type of that value at runtime is the same as 386 | the type specified in the right-hand side of the `is` pattern --- or a subclass of that type. 387 | The `is` pattern behaves like the `is` operator in that they both perform a type cast 388 | but discard the returned type. 389 | 390 | The `as` pattern matches a value if the type of that value at runtime is the same as 391 | the type specified in the right-hand side of the `as` pattern --- or a subclass of that type. 392 | If the match succeeds, 393 | the type of the matched value is cast to the *pattern* specified in the right-hand side 394 | of the `as` pattern. 395 | 396 | For an example that uses a `switch` statement 397 | to match values with `is` and `as` patterns, 398 | see . 399 | 400 | > Grammar of a type casting pattern: 401 | > 402 | > *type-casting-pattern* → *is-pattern* | *as-pattern* \ 403 | > *is-pattern* → **`is`** *type* \ 404 | > *as-pattern* → *pattern* **`as`** *type* 405 | 406 | ## Expression Pattern 407 | 408 | An *expression pattern* represents the value of an expression. 409 | Expression patterns appear only in `switch` statement 410 | case labels. 411 | 412 | The expression represented by the expression pattern 413 | is compared with the value of an input expression 414 | using the pattern-matching operator (`~=`) from the Swift standard library. 415 | The matches succeeds 416 | if the `~=` operator returns `true`. By default, the `~=` operator compares 417 | two values of the same type using the `==` operator. 418 | It can also match a value with a range of values, 419 | by checking whether the value is contained within the range, 420 | as the following example shows. 421 | 422 | ```swift 423 | let point = (1, 2) 424 | switch point { 425 | case (0, 0): 426 | print("(0, 0) is at the origin.") 427 | case (-2...2, -2...2): 428 | print("(\(point.0), \(point.1)) is near the origin.") 429 | default: 430 | print("The point is at (\(point.0), \(point.1)).") 431 | } 432 | // Prints "(1, 2) is near the origin." 433 | ``` 434 | 435 | 451 | 452 | You can overload the `~=` operator to provide custom expression matching behavior. 453 | For example, you can rewrite the above example to compare the `point` expression 454 | with a string representations of points. 455 | 456 | ```swift 457 | // Overload the ~= operator to match a string with an integer. 458 | func ~= (pattern: String, value: Int) -> Bool { 459 | return pattern == "\(value)" 460 | } 461 | switch point { 462 | case ("0", "0"): 463 | print("(0, 0) is at the origin.") 464 | default: 465 | print("The point is at (\(point.0), \(point.1)).") 466 | } 467 | // Prints "The point is at (1, 2)." 468 | ``` 469 | 470 | 487 | 488 | > Grammar of an expression pattern: 489 | > 490 | > *expression-pattern* → *expression* 491 | 492 | 501 | -------------------------------------------------------------------------------- /TSPL.docc/The-Swift-Programming-Language.md: -------------------------------------------------------------------------------- 1 | # The Swift Programming Language (6.1) 2 | 3 | @Metadata { 4 | @TechnologyRoot 5 | } 6 | 7 | @Options(scope: global) { 8 | @AutomaticSeeAlso(disabled) 9 | @AutomaticTitleHeading(disabled) 10 | @AutomaticArticleSubheading(disabled) 11 | } 12 | 13 | ## Topics 14 | 15 | ### Welcome to Swift 16 | 17 | - 18 | - 19 | - 20 | 21 | ### Language Guide 22 | 23 | - 24 | - 25 | - 26 | - 27 | - 28 | - 29 | - 30 | - 31 | - 32 | - 33 | - 34 | - 35 | - 36 | - 37 | - 38 | - 39 | - 40 | - 41 | - 42 | - 43 | - 44 | - 45 | - 46 | - 47 | - 48 | - 49 | - 50 | - 51 | - 52 | 53 | ### Language Reference 54 | 55 | - 56 | - 57 | - 58 | - 59 | - 60 | - 61 | - 62 | - 63 | - 64 | - 65 | 66 | ### Revision History 67 | 68 | - 69 | 70 | 79 | -------------------------------------------------------------------------------- /TSPL.docc/footer.html: -------------------------------------------------------------------------------- 1 | 10 | 11 | 12 |
13 |
14 |
15 | 16 |

This document is made available under a Creative Commons Attribution 4.0 International (CC BY 4.0) License.

17 |

Swift and the Swift logo are trademarks of Apple Inc.

18 |

19 | Privacy Policy 20 | Cookies 21 |

22 |
23 | 49 |
50 | 114 | 150 |
151 | -------------------------------------------------------------------------------- /TSPL.docc/header-publish.html: -------------------------------------------------------------------------------- 1 | 10 | 11 | 32 | -------------------------------------------------------------------------------- /TSPL.docc/header-staging.html: -------------------------------------------------------------------------------- 1 | 10 | 11 | 25 | -------------------------------------------------------------------------------- /bin/find_screenshot_changes: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env zsh 2 | 3 | setopt ERR_EXIT NO_UNSET PIPE_FAIL 4 | 5 | # This source file is part of the Swift.org open source project 6 | # 7 | # Copyright (c) 2023 Apple Inc. and the Swift project authors 8 | # Licensed under Apache License v2.0 with Runtime Library Exception 9 | # 10 | # See https://swift.org/LICENSE.txt for license information 11 | # See https://swift.org/CONTRIBUTORS.txt for Swift project authors 12 | 13 | # This script helps identify changes that show up in screenshots. 14 | # 15 | # Set $COMMIT to the oldest commit this script should consider: 16 | # ideally, that's the commit when the current screenshots were taken. 17 | # 18 | # Lines in the output that start with whitespace are unchanged since $COMMIT. 19 | # Lines that start with a commit ID were changed in that commit, after $COMMIT. 20 | # 21 | # To check whether we need to re-shoot the screenshots, 22 | # run this script and check whether any lines start with commit IDs. 23 | # For example: 24 | # 25 | # ./bin/find_screenshot_changes.zsh | grep -v '^ ' 26 | # 27 | # To show those commits that made scheenshot changes: 28 | # 29 | # ./bin/find_screenshot_changes.zsh | 30 | # cut -d ' ' -f 1 | 31 | # sort -u | 32 | # xargs -L1 git --no-pager log -1 33 | 34 | BEGIN='' 35 | END='' 36 | 37 | # The commit when these comment markers were originally added. 38 | # COMMIT=64627a260ed600015dbad1a853d8b85f611b61d4 39 | 40 | # The commit when the content was converted from RST to markdown. 41 | COMMIT=96f0925407c6bd9eadd9d58d253bad3e1ef7a9f2 42 | 43 | cd Sources/TSPL/TSPL.docc 44 | git grep --files-with-matches $BEGIN | while IFS= read -r FILE 45 | do 46 | git --no-pager blame -bs $COMMIT.. -L /$BEGIN/,/$END/ $FILE 47 | echo 48 | echo 49 | done 50 | -------------------------------------------------------------------------------- /bin/preflight: -------------------------------------------------------------------------------- 1 | #! /bin/zsh 2 | 3 | # This source file is part of the Swift.org open source project 4 | # 5 | # Copyright (c) 2023 Apple Inc. and the Swift project authors 6 | # Licensed under Apache License v2.0 with Runtime Library Exception 7 | # 8 | # See https://swift.org/LICENSE.txt for license information 9 | # See https://swift.org/CONTRIBUTORS.txt for Swift project authors 10 | 11 | 12 | # Basic checks before building the book for publication. 13 | 14 | setopt ERR_EXIT NO_UNSET PIPE_FAIL 15 | 16 | exit_status=0 17 | 18 | if [[ -n "$(git status --porcelain)" ]] 19 | then 20 | echo "Error: Git repository has uncommitted changes." 21 | exit_status=1 22 | fi 23 | 24 | # The publication scripts copy in the appropriate header template for 25 | # draft or publication builds. 26 | if [[ -e "TSPL.docc/header.html" ]] 27 | then 28 | echo "Error: header.html already exists." 29 | exit_status=1 30 | fi 31 | 32 | # Check for tasks that were marked as needing to be resolved before 33 | # merging the feature branch to 'main' or a release branch. 34 | # 35 | # Odd quoting below prevents the check itself from matching. 36 | if git grep -I X""XX 37 | then 38 | echo "Error: X""XX marks unresolved tasks." 39 | exit_status=1 40 | fi 41 | 42 | echo "Checking links..." 43 | cmark --to xml TSPL.docc/*/*.md | 44 | xpath -q -n -e '//link/@destination' | 45 | sort -u | cut -f2 -d= | grep -v '^"doc:' | sed 's/^"//; s/"$//' | 46 | while read url 47 | do 48 | if curl --silent --output /dev/null --location --fail --head $url 49 | then 50 | echo " $url" 51 | else 52 | echo "BAD: $url" 53 | exit_status=1 54 | fi 55 | done 56 | 57 | exit $exit_status 58 | -------------------------------------------------------------------------------- /bin/publish-book: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | # This source file is part of the Swift.org open source project 4 | # 5 | # Copyright (c) 2023 Apple Inc. and the Swift project authors 6 | # Licensed under Apache License v2.0 with Runtime Library Exception 7 | # 8 | # See https://swift.org/LICENSE.txt for license information 9 | # See https://swift.org/CONTRIBUTORS.txt for Swift project authors 10 | 11 | # Prepares a version of the book suitable for publication on swift.org. 12 | 13 | set -eux 14 | 15 | # Pretty print DocC JSON output, so that it has a stable ordering and 16 | # can be diffed. This lets us determine whether rebuilding resulted in 17 | # any changes to the content. 18 | export DOCC_JSON_PRETTYPRINT="YES" 19 | 20 | output="./swift-book" 21 | 22 | # Start at the top level directory of the repository. 23 | cd "$(git rev-parse --show-toplevel)" 24 | 25 | # The published version of the book gets the swift.org header. 26 | cp -n TSPL.docc/header-publish.html TSPL.docc/header.html 27 | 28 | xcrun docc convert \ 29 | --experimental-enable-custom-templates \ 30 | --hosting-base-path swift-book \ 31 | --output-path "$output" \ 32 | TSPL.docc 33 | 34 | rm TSPL.docc/header.html 35 | 36 | # Copy the redirect pages into every location where the legacy RST-based 37 | # pipeline created an HTML page, to keep links to those chapters and 38 | # sections working. 39 | cp -r bin/redirects/GuidedTour "$output" 40 | cp -r bin/redirects/LanguageGuide "$output" 41 | cp -r bin/redirects/ReferenceManual "$output" 42 | cp -r bin/redirects/RevisionHistory "$output" 43 | cp -r bin/redirects/index.html "$output" 44 | 45 | # Add a redirect page from swift.org/swift-book/documentation/. 46 | cp -r bin/redirects/documentation/index.html "$output/documentation/" 47 | -------------------------------------------------------------------------------- /bin/redirects/documentation/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | The Swift Programming Language: Redirect 4 | 5 | 6 | 7 |
8 | This content has moved; redirecting to the 9 | new location. 10 | 16 |
17 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /bin/redirects/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | The Swift Programming Language: Redirect 4 | 5 | 6 | 7 |
8 | This content has moved; redirecting to the 9 | new location. 10 | 16 |
17 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /bin/update-book-preview: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | # This source file is part of the Swift.org open source project 4 | # 5 | # Copyright (c) 2022 Apple Inc. and the Swift project authors 6 | # Licensed under Apache License v2.0 with Runtime Library Exception 7 | # 8 | # See https://swift.org/LICENSE.txt for license information 9 | # See https://swift.org/CONTRIBUTORS.txt for Swift project authors 10 | 11 | # Updates the GitHub Pages documentation site that's published from the 'docs' 12 | # subdirectory in the 'gh-pages' branch of this repository. 13 | # 14 | # This script should be run by someone with commit access to the 'gh-pages' branch 15 | # at a regular frequency so that the documentation content on the GitHub Pages site 16 | # is up-to-date with the content in this repo. 17 | 18 | set -eux 19 | 20 | REMOTE=${1:-origin} 21 | CURRENT_COMMIT_HASH="$(git rev-parse --short HEAD)" 22 | 23 | # Start at the top level directory of the repository. 24 | cd "$(git rev-parse --show-toplevel)" 25 | 26 | # Check out the 'gh-pages' branch in a subdirectory. 27 | git worktree add --checkout gh-pages "$REMOTE"/gh-pages 28 | 29 | # Pretty print DocC JSON output, so that it has a stable ordering and 30 | # can be diffed. This lets us determine whether rebuilding resulted in 31 | # any changes to the content. 32 | export DOCC_JSON_PRETTYPRINT="YES" 33 | 34 | # The staging version of the book gets the staging header. 35 | cp -n TSPL.docc/header-staging.html TSPL.docc/header.html 36 | 37 | # Build documentation, writing output in the gh-pages/docs subdirectory. 38 | xcrun docc convert \ 39 | --experimental-enable-custom-templates \ 40 | --hosting-base-path swift-book \ 41 | --output-path "./gh-pages/docs" \ 42 | TSPL.docc 43 | 44 | rm TSPL.docc/header.html 45 | 46 | # Commit and push our changes to the gh-pages branch 47 | pushd gh-pages 48 | git add docs 49 | 50 | if [[ -n "$(git status --porcelain)" ]] 51 | then 52 | echo "Found documentation changes." 53 | echo "Committing the changes to the 'gh-pages' branch and pushing to $REMOTE." 54 | git commit -m "Update GitHub Pages documentation site to '$CURRENT_COMMIT_HASH'." 55 | echo 56 | git push "$REMOTE" HEAD:gh-pages 57 | else 58 | echo "No documentation changes found." 59 | fi 60 | 61 | popd 62 | 63 | git worktree remove gh-pages 64 | --------------------------------------------------------------------------------