Giter VIP home page Giter VIP logo

swift-book's Introduction

The Swift Programming Language

This repository contains the source for The Swift Programming Language (sometimes abbreviated as TSPL), which is published on docs.swift.org and built using Swift-DocC.

Contributing

For small changes, like typo fixes and changes to a few paragraphs, fork this repository and make a pull request.

A formal contribution process for this document is still in development. In the meantime, start a pitch thread in the Swift forums for larger changes to discuss your approach and identify possible issues before you invest a lot of time in writing.

Content in this book follows Apple Style Guide and this book’s style guide.

File bugs about the content using the issues page on Github.

Discussions and contributions follow the Swift Code of Conduct.

For more information, see Contributing to The Swift Programming Language.

Building

Run docc preview TSPL.docc in this repository's root directory.

After running DocC, open the link that docc outputs to display a local preview in your browser.

Note:

If you installed DocC by downloading a toolchain from Swift.org, docc is located in usr/bin/, relative to the installation path of the toolchain. Make sure your shell's PATH environment variable includes that directory.

If you installed DocC by downloading Xcode, run xcrun docc preview TSPL.docc instead.

swift-book's People

Contributors

amartini51 avatar daveaddey avatar bjlanier avatar krilnon avatar natecook1000 avatar kyle-ye avatar ianthetechie avatar sajjon avatar bbiguduk avatar natikgadzhi avatar es-kumagai avatar bytedriver avatar cthielen avatar urcades avatar samsung-ga avatar stzn avatar tbkka avatar saptarshisarkar12 avatar ofirmiron avatar gwynne avatar etcwilde avatar gio3k avatar flbn avatar yemibox51 avatar e78l avatar tkrajacic avatar pbrewczynski avatar parispittman avatar mattmassicotte avatar ldct avatar

Stargazers

Jasmine Montrichard avatar Karam avatar  avatar  avatar Abhijeet Singh avatar Coen ten Thije Boonkkamp avatar Lex Koby avatar aiiuii avatar Volkan Sel avatar Vaida avatar  avatar ReadMyName avatar  avatar Peter Cammeraat avatar  avatar Matt Price avatar BrockG avatar astrophor avatar  avatar  Thomas Bui-Tho avatar Ken Honda avatar Jeremy Pinnix avatar  avatar Павел Оливейра avatar Dohyeon Kim avatar Marta Reitmajer avatar Josh Katayev avatar Muzamil Bashir avatar Vlad Isan avatar James L Avakian avatar Nikita Makarov avatar Stefan Herold avatar  avatar Russell Salazar avatar cc avatar  avatar 花万里Waylon avatar Nuhu Sulemana avatar LaboriousCode avatar  avatar Logan Shire avatar  avatar Filip Jaskovic avatar Fito Toledano avatar  avatar Achsuthan avatar Jaykrushna Solanki avatar Yemi Agesin avatar Nguyen Huu Anh Tuan avatar  avatar Nicolò Curioni avatar iknowmagic avatar Alex Rybachev avatar Matt F. avatar Sudan Chapagain avatar Nnamdi Chidera Emmanuel avatar Antonio Galvan Rojas avatar  avatar Ryan avatar Tyler Miller avatar ddd avatar Frederique Hsu (徐赞) avatar James Phipps avatar  avatar  avatar Mike Schwab avatar  avatar Igor Tarasenko avatar Andreas Koslowski avatar Przemysław Dąbek avatar Saihaj Law avatar Kvar Izunia avatar Ethan Wickstrom avatar JimTsai avatar Mitch Lang avatar Saqib Saleem avatar Minh avatar Lobo avatar  avatar Xiaoyu Wang avatar Summer avatar Jörg Kreß avatar Bogdan Stăiculescu avatar talkbear avatar qqfunc avatar Ari S. avatar Anthony avatar Igor Pancheski avatar Keunreol Park avatar  avatar Nico avatar Nick Banks avatar BHARATH KUMAR.S avatar Jie avatar PutPutCars avatar Felip Reguant avatar  avatar Oscar Byström Ericsson avatar Seki Rocc avatar Amol Budhiraja avatar

Watchers

Chris Hanson avatar Daniel A. Steffen avatar Pavel Yaskevich avatar Jacob Xiao avatar Bill Dudney avatar David Owens II avatar Mattijs Hoitink avatar Aura Lily Vulcano avatar Shawn Hyam avatar Zsolt Kiraly avatar Saleem Abdulrasool avatar Slava Pestov avatar Chuck Toporek avatar Vedant Kumar avatar Jim Turner avatar Konrad `ktoso` Malawski avatar Rintaro Ishizaki avatar Joe Groff avatar Alexander avatar Tim Isted avatar Ben D. Jones avatar Richard Stelling avatar Connor Wakamo avatar Jonathan Hendry avatar Quinn Taylor avatar Michael Spencer avatar Mike Ash avatar  avatar Sam Page avatar Karoy Lorentey avatar Marin Todorov avatar Stephen Canon avatar HoNooD avatar Daniel Fowler avatar Euan Harris avatar  avatar Alex Lorenz avatar James Cloos avatar Richard Wei avatar Tim Triemstra avatar  avatar Simon Evans avatar Dmitri Gribenko avatar Dominic Morneau avatar Kuba (Brecka) Mracek avatar Paul Lettieri avatar Jake Petroules avatar Patrick Pijnappel avatar Sam Lazarus avatar Jerry Wong avatar Joe avatar Robert Widmann avatar Owen Voorhees avatar Bino George avatar Xi Ge avatar Adrian Prantl avatar Venkatesh Sriram avatar Tim Kolecke avatar Ellie Shin avatar Mishal Shah avatar  avatar  avatar Joshua avatar Vanson avatar Min-Yih Hsu avatar Kishore Pusukuri avatar Paulo Mattos avatar brian flagg avatar Roy Sundahl avatar  avatar Charles Hu avatar Ger O'Donnell avatar Pushkar N Kulkarni avatar Malavika Samak avatar Gustavo Cairo avatar  avatar Benjamin Herzog avatar  avatar Bhargav Gurlanka avatar Kenneth Simpson avatar  avatar Sylvain LAFRASSE avatar Grzegorz George Pawelczak avatar Gogul Balakrishnan avatar Ethan Kusters avatar Kristopher Phillips avatar  avatar Guido Soranzio avatar Matt Eaton avatar Lawrence Gimenez avatar Emil Pedersen avatar Ben Cohen avatar David Cummings avatar Kshitij Jain avatar Mary Kate Reid avatar Suraj avatar Ehud Adler avatar Harjas Monga avatar Holly Borla avatar  avatar

swift-book's Issues

Claiming authorship of redacted contributions

As part of releasing the commit history of the book, we redacted the names of some previous contributors to preserve their privacy. If we redacted your name and you would like acknowledgement, please comment on this issue and include the account info you want to use for attribution.

A Tiny Prose Mistake in Associated Values in Enumerations

Location

https://docs.swift.org/swift-book/documentation/the-swift-programming-language/enumerations/#Associated-Values

Description

In the link above, you can find a sentence that explains extracting associated values through switch statements in the section "Associated Values" in the chapter "Enumerations" as follow:

If all of the associated values for an enumeration case are extracted as constants, or if all are extracted as variables, you can place a single var or let annotation before the case name, for brevity:

This sentence is confusing, because it sounds like we can use var annotation for constants as var comes first before let.

Correction

It is certain to infer the real meaning that var cannot be used for constants if you were reading through the document from the beginning.
However, it would be better to be written in the correct order for people visiting the section straightforwardly.

If all of the associated values for an enumeration case are extracted as constants, or if all are extracted as variables, you can place a single let or var annotation before the case name, for brevity:

Update the summary of the grammar automatically

Currently, the formal grammar is manually duplicated — each rule appears one in its section reference, and again in the summary of the grammar at the end of the reference. This would be improved by some form of automation.

A simple improvement would be to script the process of collecting the grammar, so we could run that script and generate a new Summary of the Grammar chapter after any updates to the grammar. It would be even better to run that script as part of building the book, or when the grammar changes, or to have some automated reminder that the summary has become outdated.

Add remaining redirects from the old section/subsection URLs

Because of the way Swift-DocC works, the URL we publish to must change from https://docs.swift.org/swift-book to https://docs.swift.org/documentation/swift-book. We need to set up server-side redirects on Swift.org so that links to chapters continue to work. These should be relatively straightforward.

In addition, TSPL specifies a stable ID for each heading's anchor. This is used for on-page navigation within the book, and frequently used outside of the book to provide a link directly to a specific heading. Because the DocC dialect of markdown doesn't allow us to specify an anchor's ID, all of these stable IDs will be destabilized and instead derived from the text of the section heading. (See also swiftlang/swift-docc#345)

For the second issue, we don't believe the web server can inspect the URL's fragment and offer different redirect options. It may be possible to use a bit of JavaScript on a "trampoline" page, located at the old URL, to redirect to the new URL.

rdar://96321914

Specifying a default type for associated type is only in the grammar (not the guide or reference)

Location

https://docs.swift.org/swift-book/ReferenceManual/Declarations.html#ID374

Description

For example, P2 in the following code:

protocol P1 {
    associatedtype T
}

protocol P2 {
    associatedtype T: Comparable = Int
}

// P2 is equivalent to
protocol P3 where T: Comparable {
    associatedtype T = Int
}

The reference section "Protocol Associated Type Declaration" doesn't discuss this feature, nor does the guide, and there aren't any examples showing it. Adding it to the reference first would follow our general approach.

The current grammar produces all three examples above. The rule for protocol-associated-type-declaration produces type-inheritance-clause followed by typealias-assignment, which allows the : Comparable and = Int from above.

rdar://31876806

Use hard breaks in formal grammar

Location

No response

Description

Currently, DocC doesn't render hard breaks: swiftlang/swift-docc#477

When support is added, we should change the formal grammar here to use blank lines between groups and hard breaks between definitions.

Currently, as a workaround to preserve this information, each definition is followed by a blank line in source, to make it appear on its own line in output, and groups are separated by two blank lines. So something like this:

> Grammar of a self expression:
>
> *self-expression***`self`** | *self-method-expression* | *self-subscript-expression* | *self-initializer-expression*
>
>
>
> *self-method-expression***`self`** **`.`** *identifier*
>
> *self-subscript-expression***`self`** **`[`** *function-call-argument-list* **`]`**
>
> *self-initializer-expression***`self`** **`.`** **`init`**

Should turn into something like this:

> Grammar of a self expression:
>
> *self-expression***`self`** | *self-method-expression* | *self-subscript-expression* | *self-initializer-expression*
>
> *self-method-expression***`self`** **`.`** *identifier* \
> *self-subscript-expression***`self`** **`[`** *function-call-argument-list* **`]`** \
> *self-initializer-expression***`self`** **`.`** **`init`**

Correction

No response

Improve the chapter navigation experience

The book's chapters are divided into three parts: the Guided Tour, Language Guide, and Language Reference. As a result, the automatically generated See Also sections at the end of each chapter are fairly distracting (and obviated somewhat by DocC's new sidebar). We should consider adopting some proposed DocC improvements like @AutomaticSeeAlso(disabled) and @AutomaticPagination.

rdar://101885438

Add an index of Swift keywords

Some weeks ago I posted a comment on a discussion re. documentation navigation over on the language repo. swiftlang/swift-org-website#24 (comment) and I was encouraged to repost it over here.

To summarise my original comment, the book needs to have a keyword index page which provides links to both the language discussion and grammar sections, and also bi-directional links between grammar and discussion not just for concepts. Currently, finding information on a specific keyword is a long-winded process of trial and error, and relies on a reader having a rough idea as to which category in the book a particular keyword belongs. As I commented in the link re. looking up the then unfamiliar-to-me some keyword:

The best I could do in the online version is to look in the grammar summary and CMD-F to search on the page, then follow the link to the Type reference, then lookup opaque types in the language guide for the discussion. Quite the journey.

The keyword list in the Lexical Structure is a start, but needs to be expanded to provide linking, and preferably presented in its own book section.

Since then the DocC version of the book has been recently released, and in my opinion there are now some issues related to everyday usage and navigation of the book in this new form. I understand some of these may be caused by deficiencies in DocC, but if that was the case, then the old and new versions should be available in parallel until properly provisioned. While it functions well as a text one might read cover to cover, it's now impossible to navigate around to find things, as highlighted above.

The search facility now does nothing more than return the headings as presented in the contents sidebar, ditto the 'Filter' function at the bottom of the sidebar. I can read the sidebar quicker than I can type a filter.

There now appears to be no reference at all to the PDF and ePub versions of the book on the documentation website (though ePub still available via Apple Books, but not every dev is an Apple hardware user...). I have current copies, and I can at least search in them, albeit with not as fine grained control as a keyword index gives.

Review old vs new content

As we get ready to publish the DocC version of, we’re taking a review pass over the entire book, to check for markup issues, DocC bugs, or problems with the RST-to-markdown conversion. This issue tracks which chapters have been reviewed.

Welcome to Swift:

  • About Swift (2 pages)
  • Version Compatibility (2 pages)
  • A Swift Tour (28 pages)

Language Guide:

  • The Basics (30 pages)
  • Basic Operators (17 pages)
  • Strings and Characters (25 pages)
  • Collection Types (22 pages)
  • Control Flow (33 pages)
  • Functions (19 pages)
  • Closures (19 pages)
  • Enumerations (13 pages)
  • Structures and Classes (11 pages)
  • Properties (28 pages)
  • Methods (10 pages)
  • Subscripts (7 pages)
  • Inheritance (9 pages)
  • Initialization (43 pages)
  • Deinitialization (5 pages)
  • Optional Chaining (14 pages)
  • Error Handling (11 pages)
  • Concurrency (15 pages)
  • Type Casting (8 pages)
  • Nested Types (4 pages)
  • Extensions (10 pages)
  • Protocols (36 pages)
  • Generics (30 pages)
  • Opaque Types (10 pages)
  • Automatic Reference Counting (27 pages)
  • Memory Safety (9 pages)
  • Access Control (18 pages)
  • Advanced Operators (25 pages)

Language Reference:

  • About the Language Reference (2 pages)
  • Lexical Structure (18 pages)
  • Types (20 pages)
  • Expressions (43 pages)
  • Statements (26 pages)
  • Declarations (61 pages)
  • Attributes (32 pages)
  • Patterns (9 pages)
  • Generic Parameters and Arguments (6 pages)
  • Summary of the Grammar (29 pages)

Revision History:

  • Document Revision History (22 pages)

Incorrect text in the unownedOptionalReference diagram

Location

The page in the docs where it appears:
https://docs.swift.org/swift-book/documentation/the-swift-programming-language/automaticreferencecounting#Unowned-Optional-References

The actual files in the repository:
https://github.com/apple/swift-book/blob/main/TSPL.docc/Assets/[email protected]
https://github.com/apple/swift-book/blob/main/TSPL.docc/Assets/[email protected]

Description

The 3rd course is named "p" in the diagram, which doesn't match the example code above it.

Correction

The 3rd course should be named "Caring for Tropical Plants".

rdar://109160486

Linebreaks?

Currently the content contains a lot of manual line breaks.

Take a look at the rendered first paragraph of the current website:

Screenshot 2022-08-30 at 21 04 31

And now take a look at the content source:

Swift is a new programming language for iOS, macOS, watchOS, and tvOS app development.
Nonetheless, many parts of Swift will be familiar
from your experience of developing in C and Objective-C.

Or more clear by looking at it in Xcode, where line numbers are written our:
Screenshot 2022-08-30 at 21 05 36

Having to think about inserting line breaks manually to make it render nicely is cumbersome. It breaks flow when typing and surely it is a presentation matter? Also, it prevents dynamic width of the rendered book!

I suggest we rid the book of these manual line breaks and allow large screens to make use of its pixels!
Screenshot 2022-08-30 at 21 07 48

To summarise, my suggestion has two advantages:

  1. Writing the book becomes easier
  2. Rendering of the book becomes more powerful because we can use the full width of screens.

Restore tested code listings

The shipping book uses a custom syntax for its tests; we preserved these as DocC comments in the Markdown source, but use regular Swift code blocks to render them without running and testing the code as part of the build process. We should evaluate how to bring these tests back, potentially using Swift Snippets.

Flag warnings introduced by a PR by running a CI check

After #1, #36 and swiftlang/swift-docc#377 were resolved, currently there should be no warnings when building the newest swift-book using the newest swift-docc.

Input:
    /Users/kyle/Workspace/Github/swift-docc-project/swift-book/Sources/TSPL/TSPL.docc
Template:
    /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault
    .xctoolchain/usr/bin/../share/docc/render
==============================
Starting Local Preview Server
    Address: http://localhost:8080/
==============================
Monitoring
    /Users/kyle/Workspace/Github/swift-docc-project/swift-book/Sources/TSPL/TSPL.docc

Maybe we should consider to config a CI check to make sure a future PR will not produce any new warning or error(with --warnings-as-errors enabled on swift-docc side).

https://forums.swift.org/t/add-support-for-warnings-as-errors/59832/5

missing/broken redirect from documentation into TSPL

Location

https://docs.swift.org/swift-book/ReferenceManual/Expressions.html#ID563

referenced from
https://developer.apple.com/documentation/swift/keypath

Description

The link functions, but redirects to the top of the overall TSPL, and it's not clear how to get to the relevant information. I'm not sure you can even just to the subheading within Expressions in the reference manual, but it would help to at least redirect to Expressions in the reference section, if that's possible.

Correction

Ideally the link should direct to the subheading in Expressions: https://docs.swift.org/swift-book/documentation/the-swift-programming-language/expressions#Key-Path-Expression

Dark Mode / Light Mode in new online Swift Book

Description

I would like to point out that in the new format of the Swift Book (on Swift.org), a footer has been inserted which does not allow the dark mode/light mode switch to be seen and used. The mode therefore depends solely on the general setting of the Mac. In my case, this is definitely inconvenient because I can only use Dark Mode which (at least for me) is very annoying.

I don't know if this is the right place for this report, and if not, I apologise.

Steps to reproduce

Expected behavior

Environment

  • Swift compiler version info
  • Xcode version info
  • Deployment target:

Backtick in code voice produces a warning

In the following portion of the grammar:

> Grammar of an identifier:
>
> *identifier* → *identifier-head* *identifier-characters*_?_
>
> *identifier* → **`` ` ``** *identifier-head* *identifier-characters*_?_ **`` ` ``**

The CommonMark definition of a code voice permits one or more backticks, which supports exactly this sort of scenario where a backtick needs to appear in code voice. Additionally, escaping via backslash isn't allowed in code voice.

The issue here is a collision with DocC's extended markup using double-backticks surround links to API symbols. Currently, building with top-of-tree docc, the output is correct but we get warnings like the following:

Topic reference '`' couldn't be resolved. No local documentation matches this reference.

Section "Differences Between Opaque Types and Protocol Types" confusing regarding nesting functions that returns protocol types

Location

Chapter "Opaque Types"
Section "Differences Between Opaque Types and Protocol Types”

Description

The section says that the protoFlip(_:) function, which accepts types that conforms to the Shape protocol defined earlier in this chapter, does not nest. And code lie protoFlip(protoFlip(smallTriange)) is invalid. While it successfully compiles and works, that is contrary to the text written in this section.

The code:

import Foundation

protocol Shape {
    
    func draw() -> String
    
}

struct Triangle: Shape {
    var size: Int
    func draw() -> String {
        var result: [String] = []
        for length in 1...size {
            result.append(String(repeating: "*", count: length))
        }
        return result.joined(separator: "\n")
    }
}


struct FlippedShape<T: Shape>: Shape {
    var shape: T
    func draw() -> String {
        let lines = shape.draw().split(separator: "\n")
        return lines.reversed().joined(separator: "\n")
    }
}

struct Square: Shape {
    var size: Int
    func draw() -> String {
        let line = String(repeating: "*", count: size)
        let result = Array<String>(repeating: line, count: size)
        return result.joined(separator: "\n")
    }
}

struct Rect: Shape {
    var width: Int
    var height: Int
    
    func draw() -> String {
        let line = String(repeating: "*", count: width)
        let result = Array<String>(repeating: line, count: height)
        return result.joined(separator: "\n")
    }
}

func protoFlip<T: Shape>(_ shape: T) -> Shape {
    if shape is Square {
            return shape
        }

    return FlippedShape(shape: shape)
}

let smallTriangle = Triangle(size: 3)

let protoFlippedTriangle = protoFlip(protoFlip(protoFlip(smallTriangle))) // This code is invalid according to the text in section
print(protoFlippedTriangle.draw())

Output:

***
**
*

Correction

I think it is better to rewrite the example with a protocol that defines the requirement of the associated type.

Document default types for associated values

We don't appear to document the way you can provide a default type in an associate's type declaration. Noted in https://forums.swift.org/t/a-question-about-associatedtype-in-protocols/16168

The grammar of a protocol associated type declaration includes an optional typealias-assignment clause, but doesn't explain what the meaning of that is. An explanation could probably be added to the Associated Types section of the Generics article.

This was originally tracked by #41.

Fix building documentation warnings

  1. Warning as error
    Currently, there are 63 warnings when we try to build the documentation.

I think we should fix them and consider adding the --warning-as-error flag to the PR's CI workflow when the such ability is implemented.
https://forums.swift.org/t/add-support-for-warnings-as-errors/59832/5

  1. Fake warnings
    But it turns out the current 63 warnings are mostly useless warnings and should be fixed in swift-docc side.
  • 2.1 Maybe we should just ignore all the contents in @Comment?(about 2/3 of warnings are caused by this) cc @franklinsch
  • 2.2 There is a warning saying "Link in document summary will not be displayed" but it is actually displayed.

image

image

Env: Xcode 14.0 beta 6 with its bundled default Swift toolchain

Add alt text to figures

Previous ID SR-14465
Radar rdar://problem/76466123
Original Reporter amos (JIRA User)
Type Bug
Environment

Any web browser

Additional Detail from JIRA
Votes 0
Component/s
Labels Bug, Documentation
Assignee None
Priority Medium

md5: 636d25b780d6f98d27615d54de6badbd

Issue Description:

Many images in the language guide on docs.swift.org are missing meaningful alt text. Please fix so people using screen readers can fully experience the docs.

For example: in the strings and characters section, the image illustrating handling of indentation in multi-line strings has the image path as its alt text.

Name the ~= (pattern matching?) operator when introducing it

Previous ID SR-896
Radar None
Original Reporter douglashill (JIRA User)
Type Improvement
Additional Detail from JIRA
Votes 1
Component/s Standard Library
Labels Improvement, Documentation
Assignee None
Priority Medium

md5: fccac19dc8668e07b859568b36ae3644

Issue Description:

Reading through the Swift book in iBooks, the ~= is mentioned but not named. There are numerous advantages to having a clear name:

  • We can vocalise internally while reading and writing code. Many of us need to think using language: it is how we structure our thoughts.
  • We can vocalise while speaking (rather than writing) to other people about Swift.
  • Provides guidance on expected behaviours when overloading the operator.
  • Names are easier to search for. Most search engines (including Google and Jira) seem to ignore ~=.

I am sorry if I am missing the name somewhere; it's hard to search for.

https://docs.swift.org/swift-book/documentation/the-swift-programming-language/patterns

[SR-7931] Document short-hand form for generic type aliases

Previous ID SR-7931
Radar rdar://problem/41028037
Original Reporter @jepers
Type Improvement
Additional Detail from JIRA
Votes 0
Component/s
Labels Improvement
Assignee None
Priority Medium

md5: 1cae1d1241f8af82feb6fd18d96e0fef

Issue Description:

Related forum thread.

For example this:

typealias Map = Dictionary

is a short hand form for:

typealias Map<K: Hashable, V> = Dictionary<K, V>

according to this forum post by @slavapestov.

But afaict there doesn't seem to be any mention of this in any documentation.

So I guess it should be documented in eg this section:
https://docs.swift.org/swift-book/ReferenceManual/Declarations.html#ID361

And more generally, a lot of the behavior of type aliases, associated types and extensions is both undocumented and inconsistent/broken.

Properly documenting the intended behavior would certainly help not only us (new and seasoned) users but also the compiler devs.

Grammar doesn't include labelled string interpolation

Previous ID SR-14030
Radar rdar://problem/73014172
Original Reporter @woolsweater
Type Bug
Environment

Swift Book v5.3 on swift.org

Additional Detail from JIRA
Votes 0
Component/s
Labels Bug, Documentation
Assignee None
Priority Medium

md5: f52f6b8e5201224bbb536e153db0c38b

Issue Description:

The grammar rule for "interpolated-text-item" specifies a single expression inside parentheses:

interpolated-text-item → \ ( expression ) | quoted-text-item

but Swift actually accepts the equivalent of a tuple expression after the backslash, something like:

interpolated-text-item → \ ( interpolated-text-list ) | quoted-text-item
interpolated-text-list → interpolated-text-element | interpolated-text-element , interpolated-text-list
interpolated-text-element → expression | identifier : expression

Reference missing `await` in list of keywords

I am looking at the list under Keywords and Punctuation. I think await is missing from this list:

Keywords used in expressions and types: Any, as, catch, false, is, nil, rethrows, self, Self, super, throw, throws, true, and try.

Both try and await appear in similar places the grammar, so I think this is an error in the documentation.

Sandor Brecsok

Operator Declarations link

Location

https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html

Description

https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html has this:

For information about the operators provided by the Swift standard library, including a complete list of the operator precedence groups and associativity settings, see Operator Declarations.

links to apple page. I believe it should be linked to a page hosted on docs.swift.org.

Correction

No response

Requirement inference is not documented

Location

No response

Description

This code type checks and infers T: Hashable:

func foo<T>(_: Set<T>) {}

A more complex example; we infer T.Element: Hashable:

func foo<T: Sequence>(_: T) -> Set<Array<T.Element>> {}

I couldn't find mention of this behavior anywhere in TSPL.

Motivation

No response

Alternatives Considered

No response

Access Control: Declarations with no explicit specifier use the enclosing declaration's level, not private

Previous ID SR-15597
Radar None
Original Reporter Saurabh Pote (JIRA User)
Type Bug

Attachment: Download

Environment

Playground - Xcode 13.1

Additional Detail from JIRA
Votes 0
Component/s swift
Labels Bug
Assignee None
Priority Medium

md5: 3ddc3cc79f130a6791d115057efa79a2

Issue Description:

The swift documentation states that for a private class, a method without an access control specifier will be implicitly a private method(Snapshot1_SwiftDoc) attached. However when the same is executed in a playground, the method is accessible from outside the class(Snapshot2_Playground attached). If we explicitly mark the method as private, then an error is thrown as per Snapshot3_Playground.

Version Compatibility page Swift book has incorrect information about version required for concurrency

Describe the bug

The second to last paragraph of the Version Compatibility page of the Swift book incorrectly states concurrency requires '5.7 or later'. It should state '5.5 or later'. (My guess is someone did a 'replace all'.)

The same paragraph also says to, "set a deployment target of at least iOS 15, macOS 12, tvOS 15, or watchOS 8.0" which was correct at the time Swift 5.5 was released, but since Xcode 13.2 it is possible to use Swift Concurrency (but not all the new APIs) back to "macOS Catalina 10.15, iOS 13, tvOS 13, and watchOS 6".

To Reproduce

Steps to reproduce the behavior:

  1. Go to Version Compatibility
  2. Scroll down to second to last paragraph
  3. See error

Expected behavior

State facts.

Actual behavior

State mix of old facts and new find-and-replace error.

Screenshots

image

Environment details

N/A

Swift.org version/commit hash

Swift 5.7 book (that is all I could find)

Additional context

N/A

Nesting Functions returning Protocol Types aren’t “Invalid”

Location

https://docs.swift.org/swift-book/documentation/the-swift-programming-language/opaquetypes#Differences-Between-Opaque-Types-and-Protocol-Types

Description

In the document, the Chapter "Opaque Types" describes the difference between protocol types and opaque types as function return types as follows:

Another problem with this approach is that the shape transformations don’t nest. The result of flipping a triangle is a value of type Shape, and the protoFlip(_:) function takes an argument of some type that conforms to the Shape protocol. However, a value of a protocol type doesn’t conform to that protocol; the value returned by protoFlip(_:) doesn’t conform to Shape. This means code like protoFlip(protoFlip(smallTriangle)) that applies multiple transformations is invalid because the flipped shape isn’t a valid argument to protoFlip(_:).

However, in practice, unlikely, it is valid as proven by the following example:

#if swift(>=5.8)
print("hello swift 5.8+")
#endif

protocol Shape {
    func draw() -> String
}

struct Triangle: Shape {
    var size: Int
    func draw() -> String {
        var result: [String] = []
        for length in 1...size {
            result.append(String(repeating: "*", count: length))
        }
        return result.joined(separator: "\n")
    }
}

struct FlippedShape<T: Shape>: Shape {
    var shape: T
    func draw() -> String {
        if shape is Square {
            return shape.draw()
        }
        let lines = shape.draw().split(separator: "\n")
        return lines.reversed().joined(separator: "\n")
    }
}

struct Square: Shape {
    var size: Int
    func draw() -> String {
        let line = String(repeating: "*", count: size)
        let result = Array<String>(repeating: line, count: size)
        return result.joined(separator: "\n")
    }
}

func flip<T: Shape>(_ shape: T) -> some Shape {
    return FlippedShape(shape: shape)
}

func protoFlip<T: Shape>(_ shape: T) -> Shape {
    if shape is Square {
        return shape
    }
    return FlippedShape(shape: shape)
}

let smallTriangle = Triangle(size: 3)
let nestedThing = protoFlip(protoFlip(smallTriangle))
print(nestedThing.draw())
// hello swift 5.8+
// *
// **
// ***

Discussion in here: https://forums.swift.org/t/nesting-functions-returning-protocol-types-arent-invalid-in-swift-5-8/64366

Correction

The following phrase sounds confusing:
"However, a value of a protocol type doesn’t conform to that protocol."

And it should prompt a compile error.

Add a list of language features to the reference

Is your feature request related to a problem? Please describe

As a new learner and developer, I was only able to get a limited introduction to the language through The Swift Programming Language, but there were many advanced features I couldn't learn from this document. For example, there are only a few words about Actors, and when I searched the web for tutorials, I learned that there are keywords like nonisolated. I couldn't find it in the reference document, but finally found it through a search engine in swift-evolution, where I found the proposal Improved control over actor isolation, which was implemented in 2021. I think all this is very difficult for beginner language learners.

Describe the solution you'd like

I would like to have a full list of language features in the Language Reference section of The Swift Programming Language for querying. Just like Rust's official reference document is very detailed, no matter whether the feature is newly included or not.

Describe alternatives you've considered

Update Language Guide in time just like Rust Book.

Or maintain a cheat sheet.

Additional context

Improve the navigation within the grammar

The version of TSPL currently published using the pre-DocC toolchain styles each item in the definition of a grammar rule as a link to that item's own definition. The live link makes it easy to follow a series of production rules, one step at a time.

DocC doesn't currently have the ability to link to somewhere on the page other than a heading.

[SR-12942] In-Out documentation is misleading or wrong.

Previous ID SR-12942
Radar None
Original Reporter erickpc (JIRA User)
Type Bug

Attachment: Download

Additional Detail from JIRA
Votes 0
Component/s
Labels Bug, Documentation
Assignee None
Priority Medium

md5: 40885081a51d49565b9dd89413fc2e4b

Issue Description:

The documentation here https://docs.swift.org/swift-book/ReferenceManual/Declarations.html#ID545 states:

In-out parameters are passed as follows:

  1. When the function is called, the value of the argument is copied.

  2. In the body of the function, the copy is modified.

  3. When the function returns, the copy’s value is assigned to the original argument.

By reading that, if any changes are made to the argument outside of the function between. step 1 and 3, those changes would be lost when the function returns. The scenario I'm describing would be:

  1. Pass array a `[1, 2, 3]` as an In-Out argument to function `f()`

  2. While `f()` is executing, outside the function, `a` gets modified to add another value.

  3. At this point `a` is `[1, 2, 3, 4]`

  4. When `f()` finishes executing the copy of `a` copied back to the calling context, losing the last value 4.

That's the expected behavior according to the documentation. I have this test case showing it doesn't work that way. Down below the documentation mentions an "optimization" that "satisfies all of the requirements of the copy-in copy-out model while removing the overhead of copying." That last part is misleading. This "optimization" explains the behavior I'm seeing, but if I were to "Write your code using the model given by copy-in copy-out, without depending on the call-by-reference optimization" I would be surprised the system is not working as expected.

Attached is the test case

PS: The double quotes above are to show what's in the documentation verbatim.

Add chapter abstracts

When building the book, DocC understands the first paragraph of each chapter to be an abstract for that chapter, which it renders differently from the chapter's content. For example, in navigation you see both the name of the chapter and the abstract.

The current content doesn't include abstracts, so the first paragraph of the actual content is being (incorrectly) treated as an abstract. We should go through each chapter and add abstracts at the beginning. To follow editorial guidelines, the abstract needs to be a single sentence that starts with an imperative verb.

rdar://96321054

Add a "Make a contribution" banner on footer or header

Description

To facilitate contributions, I recommend adding a "Make a contribution" banner or button to the header or footer of each page. This will allow users to easily submit pull requests if they notice any errors on that particular page. Clicking the banner/button will take them directly to the source file for that page with edit mode enabled.

For instance, if a user clicks on the "Make a contribution" banner while viewing the-swift-programming-language/aboutswift, they will be redirected to https://github.com/apple/swift-book/edit/main/TSPL.docc/GuidedTour/AboutSwift.md.

image

Motivation

Github's Open Source Doc Workflow

https://docs.github.com/

image

Publish a preview/staging version of the book

Per discussion in the docs workgroup, it'd be good to have a preview version of the DocC output that we can all look at as we work toward publishing the book on swift.org. This preview should be:

  • Published on GitHub pages, probably using a workflow like this one from swift-docc-plugin.
  • Visually distinguishable as a draft/preview version so we don't confuse people who are looking for the docs and not participating in the DocC conversion effort.

rdar://101885227

Normalize code listings to use 4 space indentation in source

Some parts of the book were written before Swift style standardized on 4 space indentation, and instead uses 3 space indentation. Under the legacy Sphinx-based publication pipeline, this wasn't an issue: code listings are syntax highlighted and reindented using SourceKit as part of publication, producing published output with 4 space indents. DocC preserves indentation, so we need to clean these up in source.

rdar://96988058

optional protocols being limited to classes that inherit from Object-C classes: compiler check?

Describe the bug

Hi, I am currently learning Swift programming language.
Optional Protocol Requirements section in the official Swift programming language document(Swift 5.7) states

Note that @objc protocols can be adopted only by classes that inherit from Objective-C classes or other @objc classes. They can’t be adopted by structures or enumerations.

and provides an example code.

@objc protocol CounterDataSource {
    @objc optional func increment(forCount count: Int) -> Int
    @objc optional var fixedIncrement: Int { get }
}

// ...

class ThreeSource: NSObject, CounterDataSource {
    let fixedIncrement = 3
}

Xcode, however, readily accepts the following code snippet which does not inherit NSObject, and compiles without any problem.

class ThreeSource: /*NSObject,*/ CounterDataSource {
    let fixedIncrement = 3
}

Then, am I to understand that the document's description on the limitation is about why optional protocol is introduced to the language in the first place, and not about what is actually enforced by the compiler?

Screenshots
Screenshot 2022-11-03 at 17 50 45

Environment (please fill out the following information)

  • OS: [macOS 13.0]
  • Xcode Version/Tag/Branch: Xcode Version 14.1 (14B47b)

Unresolved H4 links

In some places, TSPL links to a H4 as an anchor point — for example:

// In Statements.md
#### Switching Over Future Enumeration Cases

// In Attributes.md and RevisionHistory.md
<doc:Statements#Switching-Over-Future-Enumeration-Cases>

However, swift-docc currently only supports H1, H2 and H3 as an anchor to reference.

https://github.com/apple/swift-docc/blob/5fe2d1331eba2243163366e4d25259b86a44e5db/Sources/SwiftDocC/Model/DocumentationNode.swift#L113-L124

Should we update the structure of content in this repo or should this be a feature/bug on swift-docc to be fixed?

If we are going to fix it on swift-docc, should we add a flag to let the consumer decide which heading level we should add as anchor or just extend it to level 4?

Improve the presentation of grammar elements

Right now, the grammar in Language Reference is implemented using plain code listings. The shipping book includes a custom presentation for the grammar, including cross-references between different grammar elements and a page that hosts the generated summary of the grammar.

rdar://101001280

Support interactivity in "A Swift Tour"

The shipping version of A Swift Tour is available as HTML or ePUB like the rest of the book, but also as a downloadable playground to open in Xcode. The code listings were tailored to take advantage of this interactive format, suggesting changes that the reader can make to each code listing to try out parts of the language.

We should extend DocC and adopt that in TSPL, to support some interactive documentation format like a playground. Or in the interim, we could consider reframing the tour to suggest that readers copy/paste each code listing into a playground or REPL, to see the code running and to edit the code.

rdar://71373440

Top level `private` is understood as `fileprivate`

Description
A class extension that is declared as private automatically turns all methods and types declared in the extension as private. This gets rid of the need to explicitly declare each method and type declared in the extension as private. However, if a type (say, an enum) declared in the extension is explicitly declared as private (which would be unnecessary but seems to be legal), and if one of the methods in the extension takes this enum as a parameter, then the compiler requires that the method be explicitly declared as private as well.

Steps to reproduce

class Foo {}

private extension Foo {  // The extension is declared as private, so everything in it will be private as well
    private enum Bar {  // This is unnecessarily declared as private, but it seems like a legal move
        case FirstCase
    }

    // The following method takes as a parameter a type that is explicitly declared as private
    func testFunction(case: Bar) {}  // The compiler complains that this method should be declared as private, when it is already private in virtue of being inside an extension that is declared as private
}

The compiler stops complaining if the enum Bar isn't explicitly declared as private anymore. However, whether the enum Bar is explicitly declared as private or not, it will be private by virtue of being inside a private extension.

Is this a bug? To me it seems so, but if others have different opinions I'd like to hear them as well.

Environment

  • Swift compiler version info
    swift-driver version: 1.62.15 Apple Swift version 5.7.2 (swiftlang-5.7.2.135.5 clang-1400.0.29.51)
    Target: x86_64-apple-macosx12.0
  • Xcode version info
    Xcode 14.2
    Build version 14C18
  • Deployment target:
    macOS 12.0

Improve the presentation of syntax outlines

When introducing new syntax for the first time, the book uses placeholder literals to show the customizable portion(s) of the syntax being introduced. Right now, these render as regular Swift code blocks that don't have a special treatment for placeholders.

rdar://64038462

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.