diff --git a/TSPL.docc/GuidedTour/GuidedTour.md b/TSPL.docc/GuidedTour/GuidedTour.md index e3056e351..f38efe6a1 100644 --- a/TSPL.docc/GuidedTour/GuidedTour.md +++ b/TSPL.docc/GuidedTour/GuidedTour.md @@ -255,7 +255,7 @@ occupations["Jayne"] = "Public Relations" ```swifttest -> var fruits = ["strawberries", "limes", "tangerines"] -> fruits[1] = "grapes" - --- + -> var occupations = [ "Malcolm": "Captain", "Kaylee": "Mechanic", @@ -317,7 +317,7 @@ let emptyDictionary: [String: Float] = [:] ```swifttest -> let emptyArray: [String] = [] -> let emptyDictionary: [String: Float] = [:] - --- + -> let anotherEmptyArray = [String]() -> let emptyDictionary = [String: Float]() ``` @@ -432,7 +432,7 @@ if let name = optionalName { -> var optionalString: String? = "Hello" -> print(optionalString == nil) <- false - --- + -> var optionalName: String? = "John Appleseed" -> var greeting = "Hello!" -> if let name = optionalName { @@ -658,7 +658,7 @@ print(m) } -> print(n) <- 128 - --- + -> var m = 2 -> repeat { m *= 2 @@ -1132,11 +1132,11 @@ class NamedShape { -> class NamedShape { var numberOfSides: Int = 0 var name: String - --- + init(name: String) { self.name = name } - --- + func simpleDescription() -> String { return "A shape with \(numberOfSides) sides." } @@ -1202,17 +1202,17 @@ test.simpleDescription() ```swifttest -> class Square: NamedShape { var sideLength: Double - --- + init(sideLength: Double, name: String) { self.sideLength = sideLength super.init(name: name) numberOfSides = 4 } - --- + func area() -> Double { return sideLength * sideLength } - --- + override func simpleDescription() -> String { return "A square with sides of length \(sideLength)." } @@ -1276,13 +1276,13 @@ print(triangle.sideLength) ```swifttest -> class EquilateralTriangle: NamedShape { var sideLength: Double = 0.0 - --- + init(sideLength: Double, name: String) { self.sideLength = sideLength super.init(name: name) numberOfSides = 3 } - --- + var perimeter: Double { get { return 3.0 * sideLength @@ -1291,7 +1291,7 @@ print(triangle.sideLength) sideLength = newValue / 3.0 } } - --- + override func simpleDescription() -> String { return "An equilateral triangle with sides of length \(sideLength)." } @@ -1471,7 +1471,7 @@ let aceRawValue = ace.rawValue case ace = 1 case two, three, four, five, six, seven, eight, nine, ten case jack, queen, king - --- + func simpleDescription() -> String { switch self { case .ace: @@ -1562,7 +1562,7 @@ let heartsDescription = hearts.simpleDescription() ```swifttest -> enum Suit { case spades, hearts, diamonds, clubs - --- + func simpleDescription() -> String { switch self { case .spades: @@ -1679,10 +1679,10 @@ case let .failure(message): case result(String, String) case failure(String) } - --- + -> let success = ServerResponse.result("6:00 am", "8:09 pm") -> let failure = ServerResponse.failure("Out of cheese.") - --- + -> switch success { case let .result(sunrise, sunset): print("Sunrise is at \(sunrise) and sunset is at \(sunset).") @@ -1982,7 +1982,7 @@ let bDescription = b.simpleDescription -> let aDescription = a.simpleDescription >> print(aDescription) << A very simple class. Now 100% adjusted. - --- + -> struct SimpleStructure: ExampleProtocol { var simpleDescription: String = "A simple structure" mutating func adjust() { @@ -2309,13 +2309,13 @@ print(fridgeIsOpen) ```swifttest -> var fridgeIsOpen = false -> let fridgeContent = ["milk", "eggs", "leftovers"] - --- + -> func fridgeContains(_ food: String) -> Bool { fridgeIsOpen = true defer { fridgeIsOpen = false } - --- + let result = fridgeContent.contains(food) return result } diff --git a/TSPL.docc/LanguageGuide/AccessControl.md b/TSPL.docc/LanguageGuide/AccessControl.md index ceb16c6fc..0362150c1 100644 --- a/TSPL.docc/LanguageGuide/AccessControl.md +++ b/TSPL.docc/LanguageGuide/AccessControl.md @@ -195,7 +195,7 @@ private func somePrivateFunction() {} -> internal class SomeInternalClass {} -> fileprivate class SomeFilePrivateClass {} -> private class SomePrivateClass {} - --- + -> open var someOpenVariable = 0 -> public var somePublicVariable = 0 -> internal let someInternalConstant = 0 @@ -284,18 +284,18 @@ private class SomePrivateClass { // explicitly private class fileprivate func someFilePrivateMethod() {} // explicitly file-private class member private func somePrivateMethod() {} // explicitly private class member } - --- + -> class SomeInternalClass { // implicitly internal class var someInternalProperty = 0 // implicitly internal class member fileprivate func someFilePrivateMethod() {} // explicitly file-private class member private func somePrivateMethod() {} // explicitly private class member } - --- + -> fileprivate class SomeFilePrivateClass { // explicitly file-private class func someFilePrivateMethod() {} // implicitly file-private class member private func somePrivateMethod() {} // explicitly private class member } - --- + -> private class SomePrivateClass { // explicitly private class func somePrivateMethod() {} // implicitly private class member } @@ -557,7 +557,7 @@ you must explicitly declare the nested type as public. -> let publicNestedInsidePublic = PublicStruct.PublicEnumInsidePublicStruct.a -> let internalNestedInsidePublic = PublicStruct.InternalEnumInsidePublicStruct.a -> let automaticNestedInsidePublic = PublicStruct.AutomaticEnumInsidePublicStruct.a - --- + -> let internalNestedInsideInternal = InternalStruct.InternalEnumInsideInternalStruct.a -> let automaticNestedInsideInternal = InternalStruct.AutomaticEnumInsideInternalStruct.a ``` @@ -569,12 +569,12 @@ you must explicitly declare the nested type as public. ```swifttest // these are all expected to fail, because they're private to the other file -> let privateNestedInsidePublic = PublicStruct.PrivateEnumInsidePublicStruct.a - --- + -> let privateNestedInsideInternal = InternalStruct.PrivateEnumInsideInternalStruct.a - --- + -> let privateNestedInsidePrivate = PrivateStruct.PrivateEnumInsidePrivateStruct.a -> let automaticNestedInsidePrivate = PrivateStruct.AutomaticEnumInsidePrivateStruct.a - --- + !$ error: 'PrivateEnumInsidePublicStruct' is inaccessible due to 'private' protection level !! let privateNestedInsidePublic = PublicStruct.PrivateEnumInsidePublicStruct.a !! ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -615,14 +615,14 @@ you must explicitly declare the nested type as public. -> let internalNestedInsidePublic = PublicStruct.InternalEnumInsidePublicStruct.a -> let automaticNestedInsidePublic = PublicStruct.AutomaticEnumInsidePublicStruct.a -> let privateNestedInsidePublic = PublicStruct.PrivateEnumInsidePublicStruct.a - --- + -> let internalNestedInsideInternal = InternalStruct.InternalEnumInsideInternalStruct.a -> let automaticNestedInsideInternal = InternalStruct.AutomaticEnumInsideInternalStruct.a -> let privateNestedInsideInternal = InternalStruct.PrivateEnumInsideInternalStruct.a - --- + -> let privateNestedInsidePrivate = PrivateStruct.PrivateEnumInsidePrivateStruct.a -> let automaticNestedInsidePrivate = PrivateStruct.AutomaticEnumInsidePrivateStruct.a - --- + !$ error: 'InternalEnumInsidePublicStruct' is inaccessible due to 'internal' protection level !! let internalNestedInsidePublic = PublicStruct.InternalEnumInsidePublicStruct.a !! ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -701,7 +701,7 @@ internal class B: A { -> public class A { fileprivate func someMethod() {} } - --- + -> internal class B: A { override internal func someMethod() {} } @@ -734,7 +734,7 @@ internal class B: A { -> public class A { fileprivate func someMethod() {} } - --- + -> internal class B: A { override internal func someMethod() { super.someMethod() @@ -1162,7 +1162,7 @@ on any type that adopts the protocol. var publicProperty = 0 func publicMethod() {} } - --- + -> public class PublicClassConformingToInternalProtocol: InternalProtocol { var internalProperty = 0 func internalMethod() {} @@ -1190,7 +1190,7 @@ on any type that adopts the protocol. !$ error: cannot find type 'FilePrivateProtocol' in scope !! public class PublicClassConformingToFilePrivateProtocol: FilePrivateProtocol { !! ^~~~~~~~~~~~~~~~~~~ - --- + // these will fail, because PrivateProtocol isn't visible outside of its file -> public class PublicClassConformingToPrivateProtocol: PrivateProtocol { var privateProperty = 0 @@ -1440,7 +1440,7 @@ extension SomeStruct: SomeProtocol { -> struct SomeStruct { private var privateVariable = 12 } - --- + -> extension SomeStruct: SomeProtocol { func doSomething() { print(privateVariable) @@ -1474,19 +1474,19 @@ but a public type alias can't alias an internal, file-private, or private type. -> public struct PublicStruct {} -> internal struct InternalStruct {} -> private struct PrivateStruct {} - --- + -> public typealias PublicAliasOfPublicType = PublicStruct -> internal typealias InternalAliasOfPublicType = PublicStruct -> private typealias PrivateAliasOfPublicType = PublicStruct - --- + -> public typealias PublicAliasOfInternalType = InternalStruct // not allowed -> internal typealias InternalAliasOfInternalType = InternalStruct -> private typealias PrivateAliasOfInternalType = InternalStruct - --- + -> public typealias PublicAliasOfPrivateType = PrivateStruct // not allowed -> internal typealias InternalAliasOfPrivateType = PrivateStruct // not allowed -> private typealias PrivateAliasOfPrivateType = PrivateStruct - --- + !$ error: type alias cannot be declared public because its underlying type uses an internal type !! public typealias PublicAliasOfInternalType = InternalStruct // not allowed !! ^ ~~~~~~~~~~~~~~ diff --git a/TSPL.docc/LanguageGuide/AdvancedOperators.md b/TSPL.docc/LanguageGuide/AdvancedOperators.md index 7a7229ca5..e1aeadf28 100644 --- a/TSPL.docc/LanguageGuide/AdvancedOperators.md +++ b/TSPL.docc/LanguageGuide/AdvancedOperators.md @@ -701,7 +701,7 @@ extension Vector2D { -> struct Vector2D { var x = 0.0, y = 0.0 } - --- + -> extension Vector2D { static func + (left: Vector2D, right: Vector2D) -> Vector2D { return Vector2D(x: left.x + right.x, y: left.y + right.y) @@ -1028,7 +1028,7 @@ let afterDoubling = +++toBeDoubled return vector } } - --- + -> var toBeDoubled = Vector2D(x: 1.0, y: 4.0) -> let afterDoubling = +++toBeDoubled /> toBeDoubled now has values of (\(toBeDoubled.x), \(toBeDoubled.y)) @@ -1349,7 +1349,7 @@ print(personalGreeting.draw()) -> func caps(@DrawingBuilder content: () -> Drawable) -> Drawable { return AllCaps(content: content()) } - --- + -> func makeGreeting(for name: String? = nil) -> Drawable { let greeting = draw { Stars(length: 3) @@ -1369,7 +1369,7 @@ print(personalGreeting.draw()) -> let genericGreeting = makeGreeting() -> print(genericGreeting.draw()) <- ***Hello WORLD!** - --- + -> let personalGreeting = makeGreeting(for: "Ravi Patel") -> print(personalGreeting.draw()) <- ***Hello RAVI PATEL!** @@ -1539,7 +1539,7 @@ see . // static func * (scale: Double, vector: Self) -> Self static func *** (scale: Double, vector: Vector2D) -> Vector2D } - --- + -> extension Double { static func *** (scale: Double, vector: Vector2D) -> Vector2D { return Vector2D(x: scale * vector.x, y: scale * vector.y) diff --git a/TSPL.docc/LanguageGuide/AutomaticReferenceCounting.md b/TSPL.docc/LanguageGuide/AutomaticReferenceCounting.md index b4be6f5f7..cdead9db4 100644 --- a/TSPL.docc/LanguageGuide/AutomaticReferenceCounting.md +++ b/TSPL.docc/LanguageGuide/AutomaticReferenceCounting.md @@ -249,7 +249,7 @@ class Apartment { var apartment: Apartment? deinit { print("\(name) is being deinitialized") } } - --- + -> class Apartment { let unit: String init(unit: String) { self.unit = unit } @@ -475,7 +475,7 @@ class Apartment { var apartment: Apartment? deinit { print("\(name) is being deinitialized") } } - --- + -> class Apartment { let unit: String init(unit: String) { self.unit = unit } @@ -505,10 +505,10 @@ unit4A!.tenant = john ```swifttest -> var john: Person? -> var unit4A: Apartment? - --- + -> john = Person(name: "John Appleseed") -> unit4A = Apartment(unit: "4A") - --- + -> john!.apartment = unit4A -> unit4A!.tenant = john ``` @@ -673,7 +673,7 @@ class CreditCard { } deinit { print("\(name) is being deinitialized") } } - --- + -> class CreditCard { let number: UInt64 unowned let customer: Customer @@ -831,7 +831,7 @@ class Course { self.courses = [] } } - --- + -> class Course { var name: String unowned var department: Department @@ -877,11 +877,11 @@ department.courses = [intro, intermediate, advanced] ```swifttest -> let department = Department(name: "Horticulture") - --- + -> let intro = Course(name: "Survey of Plants", in: department) -> let intermediate = Course(name: "Growing Common Herbs", in: department) -> let advanced = Course(name: "Caring for Tropical Plants", in: department) - --- + -> intro.nextCourse = intermediate -> intermediate.nextCourse = advanced -> department.courses = [intro, intermediate, advanced] @@ -936,7 +936,7 @@ that other courses might have. >> let d = D(value: c! ) >> print(d.a.x, d.b?.x as Any) << 100 Optional(100) - --- + >> c = nil // Now that the C instance is deallocated, access to d.a is an error. // We manually nil out d.b, which is safe because d.b is an Optional and the @@ -1014,7 +1014,7 @@ class City { self.capitalCity = City(name: capitalName, country: self) } } - --- + -> class City { let name: String unowned let country: Country @@ -1145,10 +1145,10 @@ class HTMLElement { ```swifttest -> class HTMLElement { - --- + let name: String let text: String? - --- + lazy var asHTML: () -> String = { if let text = self.text { return "<\(self.name)>\(text)" @@ -1156,16 +1156,16 @@ class HTMLElement { return "<\(self.name) />" } } - --- + init(name: String, text: String? = nil) { self.name = name self.text = text } - --- + deinit { print("\(name) is being deinitialized") } - --- + } ``` --> @@ -1436,10 +1436,10 @@ class HTMLElement { ```swifttest -> class HTMLElement { - --- + let name: String let text: String? - --- + lazy var asHTML: () -> String = { [unowned self] in if let text = self.text { @@ -1448,16 +1448,16 @@ class HTMLElement { return "<\(self.name) />" } } - --- + init(name: String, text: String? = nil) { self.name = name self.text = text } - --- + deinit { print("\(name) is being deinitialized") } - --- + } ``` --> diff --git a/TSPL.docc/LanguageGuide/BasicOperators.md b/TSPL.docc/LanguageGuide/BasicOperators.md index 77ac27209..334ac6edd 100644 --- a/TSPL.docc/LanguageGuide/BasicOperators.md +++ b/TSPL.docc/LanguageGuide/BasicOperators.md @@ -714,7 +714,7 @@ var colorNameToUse = userDefinedColorName ?? defaultColorName ```swifttest -> let defaultColorName = "red" -> var userDefinedColorName: String? // defaults to nil - --- + -> var colorNameToUse = userDefinedColorName ?? defaultColorName /> userDefinedColorName is nil, so colorNameToUse is set to the default of \"\(colorNameToUse)\" for name in names[...2] { print(name) } diff --git a/TSPL.docc/LanguageGuide/ClassesAndStructures.md b/TSPL.docc/LanguageGuide/ClassesAndStructures.md index e286bea82..1905c2819 100644 --- a/TSPL.docc/LanguageGuide/ClassesAndStructures.md +++ b/TSPL.docc/LanguageGuide/ClassesAndStructures.md @@ -439,7 +439,7 @@ print("The remembered direction is \(rememberedDirection)") -> var currentDirection = CompassPoint.west -> let rememberedDirection = currentDirection -> currentDirection.turnNorth() - --- + -> print("The current direction is \(currentDirection)") -> print("The remembered direction is \(rememberedDirection)") <- The current direction is north diff --git a/TSPL.docc/LanguageGuide/Closures.md b/TSPL.docc/LanguageGuide/Closures.md index 423da46ad..468b2e849 100644 --- a/TSPL.docc/LanguageGuide/Closures.md +++ b/TSPL.docc/LanguageGuide/Closures.md @@ -374,15 +374,15 @@ someFunctionThatTakesAClosure() { -> func someFunctionThatTakesAClosure(closure: () -> Void) { // function body goes here } - --- + -> // Here's how you call this function without using a trailing closure: - --- + -> someFunctionThatTakesAClosure(closure: { // closure's body goes here }) - --- + -> // Here's how you call this function with a trailing closure instead: - --- + -> someFunctionThatTakesAClosure() { // trailing closure's body goes here } @@ -872,7 +872,7 @@ incrementByTen() -> alsoIncrementByTen() /> returns a value of \(r5) > let r6 = -> incrementByTen() /> returns a value of \(r6) @@ -978,7 +978,7 @@ print(instance.x) -> func someFunctionWithNonescapingClosure(closure: () -> Void) { closure() } - --- + -> class SomeClass { var x = 10 func doSomething() { @@ -986,12 +986,12 @@ print(instance.x) someFunctionWithNonescapingClosure { x = 200 } } } - --- + -> let instance = SomeClass() -> instance.doSomething() -> print(instance.x) <- 200 - --- + -> completionHandlers.first?() -> print(instance.x) <- 100 @@ -1097,7 +1097,7 @@ a mutable reference to `self` for structures. >> someFunctionWithNonescapingClosure { x = 200 } >> } >> } - --- + >> completionHandlers = [] >> var instance3 = SomeStruct() >> instance3.doSomething() @@ -1116,7 +1116,7 @@ a mutable reference to `self` for structures. >> someFunctionWithEscapingClosure { print(x) } // OK >> } >> } - --- + >> completionHandlers = [] >> var s = S() >> s.doSomething() @@ -1173,11 +1173,11 @@ print(customersInLine.count) -> var customersInLine = ["Chris", "Alex", "Ewa", "Barry", "Daniella"] -> print(customersInLine.count) <- 5 - --- + -> let customerProvider = { customersInLine.remove(at: 0) } -> print(customersInLine.count) <- 5 - --- + -> print("Now serving \(customerProvider())!") <- Now serving Chris! -> print(customersInLine.count) @@ -1311,7 +1311,7 @@ for customerProvider in customerProviders { } -> collectCustomerProviders(customersInLine.remove(at: 0)) -> collectCustomerProviders(customersInLine.remove(at: 0)) - --- + -> print("Collected \(customerProviders.count) closures.") <- Collected 2 closures. -> for customerProvider in customerProviders { diff --git a/TSPL.docc/LanguageGuide/CollectionTypes.md b/TSPL.docc/LanguageGuide/CollectionTypes.md index 59c442afd..91638150a 100644 --- a/TSPL.docc/LanguageGuide/CollectionTypes.md +++ b/TSPL.docc/LanguageGuide/CollectionTypes.md @@ -162,7 +162,7 @@ var sixDoubles = threeDoubles + anotherThreeDoubles -> var anotherThreeDoubles = Array(repeating: 2.5, count: 3) /> anotherThreeDoubles is of type [Double], and equals [\(anotherThreeDoubles[0]), \(anotherThreeDoubles[1]), \(anotherThreeDoubles[2])] var sixDoubles = threeDoubles + anotherThreeDoubles /> sixDoubles is inferred as [Double], and equals \(sixDoubles) let oddDigits: Set = [1, 3, 5, 7, 9] -> let evenDigits: Set = [0, 2, 4, 6, 8] -> let singleDigitPrimeNumbers: Set = [2, 3, 5, 7] - --- + >> let a = -> oddDigits.union(evenDigits).sorted() >> assert(a == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) @@ -998,7 +998,7 @@ farmAnimals.isDisjoint(with: cityAnimals) -> let houseAnimals: Set = ["🐶", "🐱"] -> let farmAnimals: Set = ["🐮", "🐔", "🐑", "🐶", "🐱"] -> let cityAnimals: Set = ["🐦", "🐭"] - --- + >> let aa = -> houseAnimals.isSubset(of: farmAnimals) >> assert(aa == true) @@ -1430,7 +1430,7 @@ for airportName in airports.values { } for airportName in airports.values { print("Airport name: \(airportName)") } @@ -1458,7 +1458,7 @@ let airportNames = [String](airports.values) -> let airportCodes = [String](airports.keys) /> airportCodes is [\"\(airportCodes[0])\", \"\(airportCodes[1])\"] let airportNames = [String](airports.values) /> airportNames is [\"\(airportNames[0])\", \"\(airportNames[1])\"] import Foundation - --- + >> func f() async throws { -> let handle = FileHandle.standardInput -> for try await line in handle.bytes.lines { @@ -477,7 +477,7 @@ show(photos) -> let firstPhoto = await downloadPhoto(named: photoNames[0]) -> let secondPhoto = await downloadPhoto(named: photoNames[1]) -> let thirdPhoto = await downloadPhoto(named: photoNames[2]) - --- + -> let photos = [firstPhoto, secondPhoto, thirdPhoto] -> show(photos) >> } @@ -518,7 +518,7 @@ show(photos) -> async let firstPhoto = downloadPhoto(named: photoNames[0]) -> async let secondPhoto = downloadPhoto(named: photoNames[1]) -> async let thirdPhoto = downloadPhoto(named: photoNames[2]) - --- + -> let photos = await [firstPhoto, secondPhoto, thirdPhoto] -> show(photos) >> } @@ -1286,13 +1286,13 @@ await logger.addReading(from: reading) -> struct TemperatureReading: Sendable { var measurement: Int } - --- + -> extension TemperatureLogger { func addReading(from reading: TemperatureReading) { measurements.append(reading.measurement) } } - --- + -> let logger = TemperatureLogger(label: "Tea kettle", measurement: 85) -> let reading = TemperatureReading(measurement: 45) -> await logger.addReading(from: reading) @@ -1351,7 +1351,7 @@ a file descriptor isn't safe to send across concurrency domains. -> struct FileDescriptor { -> let rawValue: CInt -> } - --- + -> @available(*, unavailable) -> extension FileDescriptor: Sendable { } >> let nonsendable: Sendable = FileDescriptor(rawValue: 10) diff --git a/TSPL.docc/LanguageGuide/ControlFlow.md b/TSPL.docc/LanguageGuide/ControlFlow.md index 72f0551ca..9bd124891 100644 --- a/TSPL.docc/LanguageGuide/ControlFlow.md +++ b/TSPL.docc/LanguageGuide/ControlFlow.md @@ -1939,17 +1939,17 @@ greet(person: ["name": "Jane", "location": "Cupertino"]) guard let name = person["name"] else { return } - --- + print("Hello \(name)!") - --- + guard let location = person["location"] else { print("I hope the weather is nice near you.") return } - --- + print("I hope the weather is nice in \(location).") } - --- + -> greet(person: ["name": "John"]) <- Hello John! <- I hope the weather is nice near you. @@ -2199,7 +2199,7 @@ func chooseBestColor() -> String { -> struct ColorPreference { var bestColor = "blue" } - --- + -> func chooseBestColor() -> String { guard #available(macOS 10.12, *) else { return "gray" @@ -2243,7 +2243,7 @@ if #unavailable(iOS 10) { } else { // Fallback code } - --- + -> if #unavailable(iOS 10) { // Fallback code } diff --git a/TSPL.docc/LanguageGuide/Enumerations.md b/TSPL.docc/LanguageGuide/Enumerations.md index e1bde155e..04add5bac 100644 --- a/TSPL.docc/LanguageGuide/Enumerations.md +++ b/TSPL.docc/LanguageGuide/Enumerations.md @@ -604,7 +604,7 @@ let sunsetDirection = CompassPoint.west.rawValue -> let earthsOrder = Planet.earth.rawValue /> earthsOrder is \(earthsOrder) let sunsetDirection = CompassPoint.west.rawValue /> sunsetDirection is \"\(sunsetDirection)\" print(evaluate(product)) <- 18 ``` diff --git a/TSPL.docc/LanguageGuide/ErrorHandling.md b/TSPL.docc/LanguageGuide/ErrorHandling.md index 2dada638a..7b4ba692c 100644 --- a/TSPL.docc/LanguageGuide/ErrorHandling.md +++ b/TSPL.docc/LanguageGuide/ErrorHandling.md @@ -142,7 +142,7 @@ func cannotThrowErrors() -> String ```swifttest -> func canThrowErrors() throws -> String >> { return "foo" } - --- + -> func cannotThrowErrors() -> String >> { return "foo" } ``` @@ -246,7 +246,7 @@ class VendingMachine { var price: Int var count: Int } - --- + -> class VendingMachine { -> var inventory = [ "Candy Bar": Item(price: 12, count: 7), @@ -254,7 +254,7 @@ class VendingMachine { "Pretzels": Item(price: 7, count: 11) ] -> var coinsDeposited = 0 - --- + -> func vend(itemNamed name: String) throws { guard let item = inventory[name] else { throw VendingMachineError.invalidSelection @@ -521,7 +521,7 @@ do { print("Couldn't buy that from the vending machine.") } } - --- + -> do { try nourish(with: "Beet-Flavored Chips") } catch { @@ -615,11 +615,11 @@ do { // ... >> return 40 -> } - --- + -> let x = try? someThrowingFunction() >> print(x as Any) << Optional(40) - --- + -> let y: Int? do { y = try someThrowingFunction() diff --git a/TSPL.docc/LanguageGuide/Functions.md b/TSPL.docc/LanguageGuide/Functions.md index 804c6d15c..7f1eb035a 100644 --- a/TSPL.docc/LanguageGuide/Functions.md +++ b/TSPL.docc/LanguageGuide/Functions.md @@ -523,7 +523,7 @@ print(anotherGreeting(for: "Dave")) } -> print(greeting(for: "Dave")) <- Hello, Dave! - --- + -> func anotherGreeting(for person: String) -> String { return "Hello, " + person + "!" } @@ -560,7 +560,7 @@ property getters can also use an implicit return. >> func testFatal() -> Int { >> fatalError("Oh no!") >> } - --- + // But not this: >> func testPrint() -> Int { >> print(13) @@ -803,10 +803,10 @@ that come after the variadic parameter. ```swifttest // Labeled, immediately after >> func f(_ a: Int..., b: String) {} - --- + // Unlabeled, not immediately after >> func g(_ a: Int..., b: String, _ c: Int) {} - --- + // Multiple >> func h(_a: Int..., b: String, _ c: Int..., d: String) {} ``` diff --git a/TSPL.docc/LanguageGuide/Generics.md b/TSPL.docc/LanguageGuide/Generics.md index f446b72a1..b03dcb0f3 100644 --- a/TSPL.docc/LanguageGuide/Generics.md +++ b/TSPL.docc/LanguageGuide/Generics.md @@ -100,7 +100,7 @@ func swapTwoDoubles(_ a: inout Double, _ b: inout Double) { a = b b = temporaryA } - --- + -> func swapTwoDoubles(_ a: inout Double, _ b: inout Double) { let temporaryA = a a = b @@ -237,7 +237,7 @@ swapTwoValues(&someString, &anotherString) -> swapTwoValues(&someInt, &anotherInt) /> someInt is now \(someInt), and anotherInt is now \(anotherInt) var someString = "hello" -> var anotherString = "world" -> swapTwoValues(&someString, &anotherString) @@ -1276,19 +1276,19 @@ func allItemsMatch -> func allItemsMatch (_ someContainer: C1, _ anotherContainer: C2) -> Bool where C1.Item == C2.Item, C1.Item: Equatable { - --- + // Check that both containers contain the same number of items. if someContainer.count != anotherContainer.count { return false } - --- + // Check each pair of items to see if they're equivalent. for i in 0.. stackOfStrings.push("uno") -> stackOfStrings.push("dos") -> stackOfStrings.push("tres") - --- + -> var arrayOfStrings = ["uno", "dos", "tres"] - --- + -> if allItemsMatch(stackOfStrings, arrayOfStrings) { print("All items match.") } else { @@ -1757,7 +1757,7 @@ protocol Container { mutating func append(_ item: Item) var count: Int { get } subscript(i: Int) -> Item { get } - --- + associatedtype Iterator: IteratorProtocol where Iterator.Element == Item func makeIterator() -> Iterator } diff --git a/TSPL.docc/LanguageGuide/Initialization.md b/TSPL.docc/LanguageGuide/Initialization.md index ff3a1bb01..c9618600e 100644 --- a/TSPL.docc/LanguageGuide/Initialization.md +++ b/TSPL.docc/LanguageGuide/Initialization.md @@ -599,7 +599,7 @@ even if it has stored properties that don't have default values. ```swifttest -> struct S { var int: Int; var string: String } -> let s = S(int: 42, string: "hello") - --- + -> struct SS { var int = 10; var string: String } -> let ss = SS(int: 42, string: "hello") ``` @@ -664,7 +664,7 @@ print(zeroByZero.width, zeroByZero.height) -> let zeroByTwo = Size(height: 2.0) -> print(zeroByTwo.width, zeroByTwo.height) <- 0.0 2.0 - --- + -> let zeroByZero = Size() -> print(zeroByZero.width, zeroByZero.height) <- 0.0 0.0 @@ -1853,15 +1853,15 @@ if valueChanged == nil { ```swifttest -> let wholeNumber: Double = 12345.0 -> let pi = 3.14159 - --- + -> if let valueMaintained = Int(exactly: wholeNumber) { print("\(wholeNumber) conversion to Int maintains value of \(valueMaintained)") } <- 12345.0 conversion to Int maintains value of 12345 - --- + -> let valueChanged = Int(exactly: pi) // valueChanged is of type Int?, not Int - --- + -> if valueChanged == nil { print("\(pi) conversion to Int doesn't maintain value") } @@ -1920,7 +1920,7 @@ if let giraffe = someCreature { ```swifttest -> let someCreature = Animal(species: "Giraffe") // someCreature is of type Animal?, not Animal - --- + -> if let giraffe = someCreature { print("An animal was initialized with a species of \(giraffe.species)") } @@ -1947,7 +1947,7 @@ if anonymousCreature == nil { ```swifttest -> let anonymousCreature = Animal(species: "") // anonymousCreature is of type Animal?, not Animal - --- + -> if anonymousCreature == nil { print("The anonymous creature couldn't be initialized") } @@ -2043,7 +2043,7 @@ if unknownUnit == nil { print("This is a defined temperature unit, so initialization succeeded.") } <- This is a defined temperature unit, so initialization succeeded. - --- + -> let unknownUnit = TemperatureUnit(symbol: "X") -> if unknownUnit == nil { print("This isn't a defined temperature unit, so initialization failed.") @@ -2089,13 +2089,13 @@ if unknownUnit == nil { -> enum TemperatureUnit: Character { case kelvin = "K", celsius = "C", fahrenheit = "F" } - --- + -> let fahrenheitUnit = TemperatureUnit(rawValue: "F") -> if fahrenheitUnit != nil { print("This is a defined temperature unit, so initialization succeeded.") } <- This is a defined temperature unit, so initialization succeeded. - --- + -> let unknownUnit = TemperatureUnit(rawValue: "X") -> if unknownUnit == nil { print("This isn't a defined temperature unit, so initialization failed.") @@ -2204,7 +2204,7 @@ class CartItem: Product { } } >> let p = Product(name: "") - --- + -> class CartItem: Product { let quantity: Int init?(name: String, quantity: Int) { diff --git a/TSPL.docc/LanguageGuide/MemorySafety.md b/TSPL.docc/LanguageGuide/MemorySafety.md index 2cd4b6999..909f93df5 100644 --- a/TSPL.docc/LanguageGuide/MemorySafety.md +++ b/TSPL.docc/LanguageGuide/MemorySafety.md @@ -50,7 +50,7 @@ print("We're number \(one)!") ```swifttest // A write access to the memory where one is stored. -> var one = 1 - --- + // A read access from the memory where one is stored. -> print("We're number \(one)!") << We're number 1! @@ -193,7 +193,7 @@ print(myNumber) -> func oneMore(than number: Int) -> Int { return number + 1 } - --- + -> var myNumber = 1 -> myNumber = oneMore(than: myNumber) -> print(myNumber) @@ -251,11 +251,11 @@ increment(&stepSize) ```swifttest -> var stepSize = 1 - --- + -> func increment(_ number: inout Int) { number += stepSize } - --- + -> increment(&stepSize) // Error: conflicting accesses to stepSize xx Simultaneous accesses to 0x10e8667d8, but modification requires exclusive access. @@ -302,7 +302,7 @@ stepSize = copyOfStepSize // Make an explicit copy. -> var copyOfStepSize = stepSize -> increment(©OfStepSize) - --- + // Update the original. -> stepSize = copyOfStepSize /> stepSize is now \(stepSize) @@ -473,7 +473,7 @@ oscar.shareHealth(with: &maria) // OK balance(&teammate.health, &health) } } - --- + -> var oscar = Player(name: "Oscar", health: 10, energy: 10) -> var maria = Player(name: "Maria", health: 5, energy: 10) -> oscar.shareHealth(with: &maria) // OK diff --git a/TSPL.docc/LanguageGuide/Methods.md b/TSPL.docc/LanguageGuide/Methods.md index ce0b6e129..570ba0814 100644 --- a/TSPL.docc/LanguageGuide/Methods.md +++ b/TSPL.docc/LanguageGuide/Methods.md @@ -488,15 +488,15 @@ struct LevelTracker { -> struct LevelTracker { static var highestUnlockedLevel = 1 var currentLevel = 1 - --- + -> static func unlock(_ level: Int) { if level > highestUnlockedLevel { highestUnlockedLevel = level } } - --- + -> static func isUnlocked(_ level: Int) -> Bool { return level <= highestUnlockedLevel } - --- + -> @discardableResult mutating func advance(to level: Int) -> Bool { if LevelTracker.isUnlocked(level) { diff --git a/TSPL.docc/LanguageGuide/NestedTypes.md b/TSPL.docc/LanguageGuide/NestedTypes.md index 0aea53317..ffc7f70db 100644 --- a/TSPL.docc/LanguageGuide/NestedTypes.md +++ b/TSPL.docc/LanguageGuide/NestedTypes.md @@ -70,12 +70,12 @@ struct BlackjackCard { ```swifttest -> struct BlackjackCard { - --- + // nested Suit enumeration enum Suit: Character { case spades = "♠", hearts = "♡", diamonds = "♢", clubs = "♣" } - --- + // nested Rank enumeration enum Rank: Int { case two = 2, three, four, five, six, seven, eight, nine, ten @@ -94,7 +94,7 @@ struct BlackjackCard { } } } - --- + // BlackjackCard properties and methods let rank: Rank, suit: Suit var description: String { diff --git a/TSPL.docc/LanguageGuide/OpaqueTypes.md b/TSPL.docc/LanguageGuide/OpaqueTypes.md index 12ba80c11..293b93d1c 100644 --- a/TSPL.docc/LanguageGuide/OpaqueTypes.md +++ b/TSPL.docc/LanguageGuide/OpaqueTypes.md @@ -60,7 +60,7 @@ print(smallTriangle.draw()) -> protocol Shape { func draw() -> String } - --- + -> struct Triangle: Shape { var size: Int func draw() -> String { @@ -257,7 +257,7 @@ print(trapezoid.draw()) return result.joined(separator: "\n") } } - --- + -> func makeTrapezoid() -> some Shape { let top = Triangle(size: 2) let middle = Square(size: 2) @@ -336,7 +336,7 @@ print(opaqueJoinedTriangles.draw()) -> func join(_ top: T, _ bottom: U) -> some Shape { JoinedShape(top: top, bottom: bottom) } - --- + -> let opaqueJoinedTriangles = join(smallTriangle, flip(smallTriangle)) -> print(opaqueJoinedTriangles.draw()) (item: T) -> C { -> func makeProtocolContainer(item: T) -> Container { return [item] } - --- + // Error: Not enough information to infer C. -> func makeProtocolContainer(item: T) -> C { return [item] diff --git a/TSPL.docc/LanguageGuide/OptionalChaining.md b/TSPL.docc/LanguageGuide/OptionalChaining.md index 5abb3c59d..dd8480621 100644 --- a/TSPL.docc/LanguageGuide/OptionalChaining.md +++ b/TSPL.docc/LanguageGuide/OptionalChaining.md @@ -60,7 +60,7 @@ class Residence { -> class Person { var residence: Residence? } - --- + -> class Residence { var numberOfRooms = 1 } @@ -462,11 +462,11 @@ john.residence?.address = createAddress() ```swifttest -> func createAddress() -> Address { print("Function was called.") - --- + let someAddress = Address() someAddress.buildingNumber = "29" someAddress.street = "Acacia Road" - --- + return someAddress } -> john.residence?.address = createAddress() @@ -657,7 +657,7 @@ if let firstRoomName = john.residence?[0].name { -> johnsHouse.rooms.append(Room(name: "Living Room")) -> johnsHouse.rooms.append(Room(name: "Kitchen")) -> john.residence = johnsHouse - --- + -> if let firstRoomName = john.residence?[0].name { print("The first room name is \(firstRoomName).") } else { @@ -795,7 +795,7 @@ if let johnsStreet = john.residence?.address?.street { -> johnsAddress.buildingName = "The Larches" -> johnsAddress.street = "Laurel Street" -> john.residence?.address = johnsAddress - --- + -> if let johnsStreet = john.residence?.address?.street { print("John's street name is \(johnsStreet).") } else { diff --git a/TSPL.docc/LanguageGuide/Properties.md b/TSPL.docc/LanguageGuide/Properties.md index b703fb62d..ae75c861c 100644 --- a/TSPL.docc/LanguageGuide/Properties.md +++ b/TSPL.docc/LanguageGuide/Properties.md @@ -240,13 +240,13 @@ manager.data.append("Some more data") >> print("the DataImporter instance for the importer property has now been created") >> } } - --- + -> class DataManager { lazy var importer = DataImporter() var data: [String] = [] // the DataManager class would provide data management functionality here } - --- + -> let manager = DataManager() -> manager.data.append("Some data") -> manager.data.append("Some more data") @@ -1023,15 +1023,15 @@ print(rectangle.height) -> @TwelveOrLess var height: Int -> @TwelveOrLess var width: Int -> } - --- + -> var rectangle = SmallRectangle() -> print(rectangle.height) <- 0 - --- + -> rectangle.height = 10 -> print(rectangle.height) <- 10 - --- + -> rectangle.height = 24 -> print(rectangle.height) <- 12 @@ -1149,12 +1149,12 @@ struct SmallNumber { -> struct SmallNumber { private var maximum: Int private var number: Int - --- + var wrappedValue: Int { get { return number } set { number = min(newValue, maximum) } } - --- + init() { maximum = 12 number = 0 @@ -1211,7 +1211,7 @@ print(zeroRectangle.height, zeroRectangle.width) -> @SmallNumber var height: Int -> @SmallNumber var width: Int -> } - --- + -> var zeroRectangle = ZeroRectangle() -> print(zeroRectangle.height, zeroRectangle.width) <- 0 0 @@ -1274,7 +1274,7 @@ print(unitRectangle.height, unitRectangle.width) -> @SmallNumber var height: Int = 1 -> @SmallNumber var width: Int = 1 -> } - --- + -> var unitRectangle = UnitRectangle() -> print(unitRectangle.height, unitRectangle.width) <- 1 1 @@ -1339,11 +1339,11 @@ print(narrowRectangle.height, narrowRectangle.width) -> @SmallNumber(wrappedValue: 2, maximum: 5) var height: Int -> @SmallNumber(wrappedValue: 3, maximum: 4) var width: Int -> } - --- + -> var narrowRectangle = NarrowRectangle() -> print(narrowRectangle.height, narrowRectangle.width) <- 2 3 - --- + -> narrowRectangle.height = 100 -> narrowRectangle.width = 100 -> print(narrowRectangle.height, narrowRectangle.width) @@ -1418,11 +1418,11 @@ print(mixedRectangle.height) -> @SmallNumber var height: Int = 1 -> @SmallNumber(maximum: 9) var width: Int = 2 -> } - --- + -> var mixedRectangle = MixedRectangle() -> print(mixedRectangle.height) <- 1 - --- + -> mixedRectangle.height = 20 -> print(mixedRectangle.height) <- 12 @@ -1500,7 +1500,7 @@ print(someStructure.$someNumber) -> struct SmallNumber { private var number: Int private(set) var projectedValue: Bool - --- + var wrappedValue: Int { get { return number } set { @@ -1513,7 +1513,7 @@ print(someStructure.$someNumber) } } } - --- + init() { self.number = 0 self.projectedValue = false @@ -1523,11 +1523,11 @@ print(someStructure.$someNumber) -> @SmallNumber var someNumber: Int -> } -> var someStructure = SomeStructure() - --- + -> someStructure.someNumber = 4 -> print(someStructure.$someNumber) <- false - --- + -> someStructure.someNumber = 55 -> print(someStructure.$someNumber) <- true @@ -1588,11 +1588,11 @@ struct SizedRectangle { -> enum Size { case small, large } - --- + -> struct SizedRectangle { -> @SmallNumber var height: Int -> @SmallNumber var width: Int - --- + mutating func resize(to size: Size) -> Bool { switch size { case .small: @@ -1705,11 +1705,11 @@ func someFunction() { ```swifttest -> func someFunction() { -> @SmallNumber var myNumber: Int = 0 - --- + myNumber = 10 // now myNumber is 10 >> print(myNumber) - --- + myNumber = 24 // now myNumber is 12 >> print(myNumber) diff --git a/TSPL.docc/LanguageGuide/Protocols.md b/TSPL.docc/LanguageGuide/Protocols.md index 1bc0d29d4..a3f9c99b2 100644 --- a/TSPL.docc/LanguageGuide/Protocols.md +++ b/TSPL.docc/LanguageGuide/Protocols.md @@ -646,13 +646,13 @@ class SomeSubClass: SomeSuperClass, SomeProtocol { -> protocol SomeProtocol { init() } - --- + -> class SomeSuperClass { init() { // initializer implementation goes here } } - --- + -> class SomeSubClass: SomeSuperClass, SomeProtocol { // "required" from SomeProtocol conformance; "override" from SomeSuperClass required override init() { @@ -1240,7 +1240,7 @@ if twoThreeFour == anotherTwoThreeFour { -> struct Vector3D: Equatable { var x = 0.0, y = 0.0, z = 0.0 } - --- + -> let twoThreeFour = Vector3D(x: 2.0, y: 3.0, z: 4.0) -> let anotherTwoThreeFour = Vector3D(x: 2.0, y: 3.0, z: 4.0) -> if twoThreeFour == anotherTwoThreeFour { @@ -1732,7 +1732,7 @@ beginConcert(in: seattle) -> func beginConcert(in location: Location & Named) { print("Hello, \(location.name)!") } - --- + -> let seattle = City(name: "Seattle", latitude: 47.6, longitude: -122.3) -> beginConcert(in: seattle) <- Hello, Seattle! diff --git a/TSPL.docc/LanguageGuide/StringsAndCharacters.md b/TSPL.docc/LanguageGuide/StringsAndCharacters.md index 16cdbe9e8..36ed95915 100644 --- a/TSPL.docc/LanguageGuide/StringsAndCharacters.md +++ b/TSPL.docc/LanguageGuide/StringsAndCharacters.md @@ -419,7 +419,7 @@ constantString += " and another Highlander" -> var variableString = "Horse" -> variableString += " and carriage" // variableString is now "Horse and carriage" - --- + -> let constantString = "Highlander" -> constantString += " and another Highlander" !$ error: left side of mutating operator isn't mutable: 'constantString' is a 'let' constant @@ -652,7 +652,7 @@ print(goodStart + end) // Prints two lines: let goodStart = """ one two @@ -938,9 +938,9 @@ print("the number of characters in \(word) is \(word.count)") -> var word = "cafe" -> print("the number of characters in \(word) is \(word.count)") <- the number of characters in cafe is 4 - --- + -> word += "\u{301}" // COMBINING ACUTE ACCENT, U+0301 - --- + -> print("the number of characters in \(word) is \(word.count)") <- the number of characters in café is 4 ``` @@ -1124,7 +1124,7 @@ welcome.insert(contentsOf: " there", at: welcome.index(before: welcome.endIndex) -> welcome.insert("!", at: welcome.endIndex) /> welcome now equals \"\(welcome)\" welcome.insert(contentsOf: " there", at: welcome.index(before: welcome.endIndex)) /> welcome now equals \"\(welcome)\" welcome.remove(at: welcome.index(before: welcome.endIndex)) /> welcome now equals \"\(welcome)\" let range = welcome.index(welcome.endIndex, offsetBy: -6).. welcome.removeSubrange(range) /> welcome now equals \"\(welcome)\" @@ -1206,7 +1206,7 @@ let newString = String(beginning) -> let beginning = greeting[.. beginning is \"\(beginning)\" let newString = String(beginning) ``` @@ -1350,10 +1350,10 @@ if eAcuteQuestion == combinedEAcuteQuestion { ```swifttest // "Voulez-vous un café?" using LATIN SMALL LETTER E WITH ACUTE -> let eAcuteQuestion = "Voulez-vous un caf\u{E9}?" - --- + // "Voulez-vous un café?" using LATIN SMALL LETTER E and COMBINING ACUTE ACCENT -> let combinedEAcuteQuestion = "Voulez-vous un caf\u{65}\u{301}?" - --- + -> if eAcuteQuestion == combinedEAcuteQuestion { print("These two strings are considered equal") } @@ -1385,10 +1385,10 @@ if latinCapitalLetterA != cyrillicCapitalLetterA { ```swifttest -> let latinCapitalLetterA: Character = "\u{41}" >> assert(latinCapitalLetterA == "A") - --- + -> let cyrillicCapitalLetterA: Character = "\u{0410}" >> assert(cyrillicCapitalLetterA == "А") - --- + -> if latinCapitalLetterA != cyrillicCapitalLetterA { print("These two characters aren't equivalent.") } diff --git a/TSPL.docc/LanguageGuide/TheBasics.md b/TSPL.docc/LanguageGuide/TheBasics.md index 0c1568893..25655022e 100644 --- a/TSPL.docc/LanguageGuide/TheBasics.md +++ b/TSPL.docc/LanguageGuide/TheBasics.md @@ -1548,7 +1548,7 @@ if let firstNumber = Int("4") { print("\(firstNumber) < \(secondNumber) < 100") } <- 4 < 42 < 100 - --- + -> if let firstNumber = Int("4") { if let secondNumber = Int("42") { if firstNumber < secondNumber && secondNumber < 100 { @@ -1696,7 +1696,7 @@ let implicitString: String = assumedString // Unwrapped automatically ```swifttest -> let possibleString: String? = "An optional string." -> let forcedString: String = possibleString! // requires an exclamation point - --- + -> let assumedString: String! = "An implicitly unwrapped optional string." -> let implicitString: String = assumedString // no need for an exclamation point ``` @@ -1883,7 +1883,7 @@ do { // ... } >> func eatASandwich() {} - --- + -> do { try makeASandwich() eatASandwich() diff --git a/TSPL.docc/LanguageGuide/TypeCasting.md b/TSPL.docc/LanguageGuide/TypeCasting.md index 360dfcafe..ddc4dde43 100644 --- a/TSPL.docc/LanguageGuide/TypeCasting.md +++ b/TSPL.docc/LanguageGuide/TypeCasting.md @@ -87,7 +87,7 @@ class Song: MediaItem { super.init(name: name) } } - --- + -> class Song: MediaItem { var artist: String init(name: String, artist: String) { @@ -175,7 +175,7 @@ print("Media library contains \(movieCount) movies and \(songCount) songs") ```swifttest -> var movieCount = 0 -> var songCount = 0 - --- + -> for item in library { if item is Movie { movieCount += 1 @@ -183,7 +183,7 @@ print("Media library contains \(movieCount) movies and \(songCount) songs") songCount += 1 } } - --- + -> print("Media library contains \(movieCount) movies and \(songCount) songs") <- Media library contains 2 movies and 3 songs ``` @@ -265,7 +265,7 @@ for item in library { print("Song: \(song.name), by \(song.artist)") } } - --- + String in "Hello, \(name)" }) ```swifttest -> var things: [Any] = [] - --- + -> things.append(0) -> things.append(0.0) -> things.append(42) @@ -441,7 +441,7 @@ for thing in things { print("something else") } } - --- + protocol MyRenamedProtocol { // protocol definition } - --- + -> @available(*, unavailable, renamed: "MyRenamedProtocol") typealias MyProtocol = MyRenamedProtocol ``` @@ -488,16 +488,16 @@ dial.dynamicallyCall(withArguments: [4, 1, 1]) } } } - --- + -> let dial = TelephoneExchange() - --- + -> // Use a dynamic method call. -> dial(4, 1, 1) <- Get Swift help on forums.swift.org - --- + -> dial(8, 6, 7, 5, 3, 0, 9) <- Unrecognized number - --- + -> // Call the underlying method directly. -> dial.dynamicallyCall(withArguments: [4, 1, 1]) << Get Swift help on forums.swift.org @@ -548,7 +548,7 @@ print(repeatLabels(a: 1, b: 2, c: 3, b: 2, a: 1)) .joined(separator: "\n") } } - --- + -> let repeatLabels = Repeater() -> print(repeatLabels(a: 1, b: 2, c: 3, b: 2, a: 1)) let s = DynamicStruct() - --- + // Use dynamic member lookup. -> let dynamic = s.someDynamicMember -> print(dynamic) <- 325 - --- + // Call the underlying subscript directly. -> let equivalent = s[dynamicMember: "someDynamicMember"] -> print(dynamic == equivalent) @@ -715,7 +715,7 @@ print(wrapper.x) ```swifttest -> struct Point { var x, y: Int } - --- + -> @dynamicMemberLookup struct PassthroughWrapper { var value: Value @@ -723,7 +723,7 @@ print(wrapper.x) get { return value[keyPath: member] } } } - --- + -> let point = Point(x: 381, y: 431) -> let wrapper = PassthroughWrapper(value: point) -> print(wrapper.x) @@ -1496,14 +1496,14 @@ struct SomeStruct { self.someValue = custom } } - --- + -> struct SomeStruct { -> // Uses init() -> @SomeWrapper var a: Int - --- + -> // Uses init(wrappedValue:) -> @SomeWrapper var b = 10 - --- + -> // Both use init(wrappedValue:custom:) -> @SomeWrapper(custom: 98.7) var c = 30 -> @SomeWrapper(wrappedValue: 30, custom: 98.7) var d @@ -1577,7 +1577,7 @@ s.$x.wrapper // WrapperWithProjection value -> struct SomeProjection { var wrapper: WrapperWithProjection } - --- + -> struct SomeStruct { -> @WrapperWithProjection var x = 123 -> } @@ -1966,7 +1966,7 @@ into code that calls the static methods of the result builder type: } << Building second... [32] << Building first... [32] - --- + -> var manualConditional: [Int] -> if someNumber < 12 { let partialResult = ArrayBuilder.buildExpression(31) @@ -2014,7 +2014,7 @@ into code that calls the static methods of the result builder type: if (someNumber % 2) == 1 { 20 } } << Building optional... Optional([20]) - --- + -> var partialResult: [Int]? = nil -> if (someNumber % 2) == 1 { partialResult = ArrayBuilder.buildExpression(20) @@ -2091,7 +2091,7 @@ into code that calls the static methods of the result builder type: Line(elements: [Text("Second"), Text("Third")]) Text("Last") } - --- + -> let partialResult1 = DrawingPartialBlockBuilder.buildPartialBlock(first: Text("first")) -> let partialResult2 = DrawingPartialBlockBuilder.buildPartialBlock( accumulated: partialResult1, @@ -2135,7 +2135,7 @@ into code that calls the static methods of the result builder type: 200 300 } - --- + -> var manualBlock = ArrayBuilder.buildBlock( ArrayBuilder.buildExpression(100), ArrayBuilder.buildExpression(200), @@ -2176,7 +2176,7 @@ into code that calls the static methods of the result builder type: 100 + i } } - --- + -> var temporary: [[Int]] = [] -> for i in 5...7 { let partialResult = ArrayBuilder.buildExpression(100 + i) @@ -2212,7 +2212,7 @@ into code that calls the static methods of the result builder type: var content: Drawable func draw() -> String { return content.draw() } } - --- + -> @resultBuilder struct DrawingBuilder { static func buildBlock(_ components: D...) -> Line { @@ -2284,7 +2284,7 @@ into code that calls the static methods of the result builder type: return AnyDrawable(content: content) } } - --- + -> @DrawingBuilder var typeErasedDrawing: Drawable { if #available(macOS 99, *) { FutureText("Inside.future") diff --git a/TSPL.docc/ReferenceManual/Declarations.md b/TSPL.docc/ReferenceManual/Declarations.md index 0f723f176..06f47f466 100644 --- a/TSPL.docc/ReferenceManual/Declarations.md +++ b/TSPL.docc/ReferenceManual/Declarations.md @@ -481,7 +481,7 @@ newAndOld.x = 200 set { print("Setter was called"); xValue = newValue } } } - --- + // This subclass doesn't refer to oldValue in its observer, so the // superclass's getter is called only once to print the value. -> class New: Superclass { @@ -494,7 +494,7 @@ newAndOld.x = 200 <- Setter was called <- Getter was called <- New value 100 - --- + // This subclass refers to oldValue in its observer, so the superclass's // getter is called once before the setter, and again to print the value. -> class NewAndOld: Superclass { @@ -607,7 +607,7 @@ var dictionary2: Dictionary = [:] ```swifttest -> typealias StringDictionary = Dictionary - --- + // The following dictionaries have the same type. -> var dictionary1: StringDictionary = [:] -> var dictionary2: Dictionary = [:] @@ -688,7 +688,7 @@ func sum(_ sequence: T) -> Int where T.Element == Int { associatedtype Iterator: IteratorProtocol typealias Element = Iterator.Element } - --- + -> func sum(_ sequence: T) -> Int where T.Element == Int { // ... >> return 9000 @@ -1800,7 +1800,7 @@ let evenInts: [Number] = [0, 2, 4, 6].map(f) } -> let f = Number.integer -> // f is a function of type (Int) -> Number - --- + -> // Apply f to create an array of Number instances with integer values -> let evenInts: [Number] = [0, 2, 4, 6].map(f) ``` @@ -1891,10 +1891,10 @@ it can't contain any cases that are also marked with the `indirect` modifier. !! :1:10: error: enum case 'c' without associated value cannot be 'indirect' !! enum E { indirect case c } !! ^ - --- + -> enum E1 { indirect case c() } // This is fine, but probably shouldn't be -> enum E2 { indirect case c(Int) } // This is fine, but probably shouldn't be - --- + -> indirect enum E3 { case x } --> @@ -2667,7 +2667,7 @@ protocol SubProtocolB: SomeProtocol where SomeType: Equatable { } -> protocol SomeProtocol { associatedtype SomeType } - --- + -> protocol SubProtocolA: SomeProtocol { // This syntax produces a warning. associatedtype SomeType: Equatable @@ -2679,7 +2679,7 @@ protocol SubProtocolB: SomeProtocol where SomeType: Equatable { } !$ note: 'SomeType' declared here !! associatedtype SomeType !! ^ - --- + // This syntax is preferred. -> protocol SubProtocolB: SomeProtocol where SomeType: Equatable { } ``` @@ -3109,7 +3109,7 @@ extension String: TitledLoggable { print(self) } } - --- + protocol TitledLoggable: Loggable { static var logTitle: String { get } } @@ -3118,7 +3118,7 @@ extension String: TitledLoggable { print("\(Self.logTitle): \(self)") } } - --- + struct Pair: CustomStringConvertible { let first: T let second: T @@ -3126,14 +3126,14 @@ extension String: TitledLoggable { return "(\(first), \(second))" } } - --- + extension Pair: Loggable where T: Loggable { } extension Pair: TitledLoggable where T: TitledLoggable { static var logTitle: String { return "Pair of '\(T.logTitle)'" } } - --- + extension String: TitledLoggable { static var logTitle: String { return "String" @@ -3247,7 +3247,7 @@ extension Array: Serializable where Element == String { -> protocol Serializable { func serialize() -> Any } - --- + extension Array: Serializable where Element == Int { func serialize() -> Any { // implementation @@ -3294,7 +3294,7 @@ extension Array: Serializable where Element: SerializableInArray { -> protocol SerializableInArray { } extension Int: SerializableInArray { } extension String: SerializableInArray { } - --- + -> extension Array: Serializable where Element: SerializableInArray { func serialize() -> Any { // implementation @@ -3349,14 +3349,14 @@ extension Array: MarkedLoggable where Element: MarkedLoggable { } -> protocol MarkedLoggable: Loggable { func markAndLog() } - --- + extension MarkedLoggable { func markAndLog() { print("----------") log() } } - --- + extension Array: Loggable where Element: Loggable { } extension Array: TitledLoggable where Element: TitledLoggable { static var logTitle: String { diff --git a/TSPL.docc/ReferenceManual/Expressions.md b/TSPL.docc/ReferenceManual/Expressions.md index 0c8ab74ca..042e6fe03 100644 --- a/TSPL.docc/ReferenceManual/Expressions.md +++ b/TSPL.docc/ReferenceManual/Expressions.md @@ -124,10 +124,10 @@ sum = (try someThrowingFunction()) + anotherThrowingFunction() >> var sum = 0 // try applies to both function calls -> sum = try someThrowingFunction() + anotherThrowingFunction() - --- + // try applies to both function calls -> sum = try (someThrowingFunction() + anotherThrowingFunction()) - --- + // Error: try applies only to the first function call -> sum = (try someThrowingFunction()) + anotherThrowingFunction() !$ error: call can throw but is not marked with 'try' @@ -235,10 +235,10 @@ sum = (await someAsyncFunction()) + anotherAsyncFunction() >> var sum = 0 // await applies to both function calls -> sum = await someAsyncFunction() + anotherAsyncFunction() - --- + // await applies to both function calls -> sum = await (someAsyncFunction() + anotherAsyncFunction()) - --- + // Error: await applies only to the first function call -> sum = (await someAsyncFunction()) + anotherAsyncFunction() >> _ = sum // Suppress irrelevant written-but-not-read warning @@ -442,7 +442,7 @@ otherwise, it returns `false`. -> class Subclass: Base {} -> var s = Subclass() -> var b = Base() - --- + -> assert(s is Base) !$ warning: 'is' test is always true !! assert(s is Base) @@ -482,11 +482,11 @@ f(x as Any) -> let x = 10 -> f(x) <- Function for Int - --- + -> let y: Any = x -> f(y) <- Function for Any - --- + -> f(x as Any) <- Function for Any ``` @@ -975,13 +975,13 @@ myFunction { $0 + $1 } -> myFunction { (x: Int, y: Int) -> Int in return x + y } - --- + -> myFunction { x, y in return x + y } - --- + -> myFunction { return $0 + $1 } - --- + -> myFunction { $0 + $1 } ``` --> @@ -1050,7 +1050,7 @@ closure() -> let closure = { [a] in print(a, b) } - --- + -> a = 10 -> b = 10 -> closure() @@ -1119,7 +1119,7 @@ closure() -> let closure = { [x] in print(x.value, y.value) } - --- + -> x.value = 10 -> y.value = 10 -> closure() @@ -1152,7 +1152,7 @@ closure() var y = 7 var f: () -> Int = { [x] in x } var g: () -> Int = { [x] in x+y } - --- + -> let r0 = f() -> assert(r0 == 100) -> let r1 = g() @@ -1388,7 +1388,7 @@ and the type of `z` is convertible from `SomeSubclass` to `SomeClass`. >> let e: E = .left >> let e2: E = .left.self >> assert(e == e2) - --- + // postfix operator >> postfix operator ~ >> extension E { @@ -1401,7 +1401,7 @@ and the type of `z` is convertible from `SomeSubclass` to `SomeClass`. >> } >> let e3: E = .left~ >> assert(e3 == .right) - --- + // initializer expression >> class S { >> var num: Int @@ -1659,10 +1659,10 @@ let value = s[keyPath: pathToProperty] -> struct SomeStructure { var someValue: Int } - --- + -> let s = SomeStructure(someValue: 12) -> let pathToProperty = \SomeStructure.someValue - --- + -> let value = s[keyPath: pathToProperty] /> value is \(value) self.someProperty = someProperty -> } -> } - --- + -> let c = SomeClass(someProperty: 10) >> let r0 = -> c.observe(\.someProperty) { object, change in @@ -1769,10 +1769,10 @@ let nestedValue = nested[keyPath: nestedKeyPath] self.outer = SomeStructure(someValue: someValue) } } - --- + -> let nested = OuterStructure(someValue: 24) -> let nestedKeyPath = \OuterStructure.outer.someValue - --- + -> let nestedValue = nested[keyPath: nestedKeyPath] /> nestedValue is \(nestedValue) var index = 2 -> let path = \[String].[index] -> let fn: ([String]) -> String = { strings in strings[index] } - --- + -> print(greetings[keyPath: path]) <- bonjour -> print(fn(greetings)) <- bonjour - --- + // Setting 'index' to a new value doesn't affect 'path' -> index += 1 -> print(greetings[keyPath: path]) <- bonjour - --- + // Because 'fn' closes over 'index', it uses the new value -> print(fn(greetings)) <- 안녕 @@ -1883,7 +1883,7 @@ print(count as Any) -> let firstGreeting: String? = greetings.first -> print(firstGreeting?.count as Any) <- Optional(5) - --- + // Do the same thing using a key path. -> let count = greetings[keyPath: \[String].first?.count] -> print(count as Any) @@ -1972,7 +1972,7 @@ let descriptions2 = toDoList.filter { $0.completed }.map { $0.description } Task(description: "Buy a pirate costume.", completed: true), Task(description: "Visit Boston in the Fall.", completed: false), ] - --- + // Both approaches below are equivalent. -> let descriptions = toDoList.filter(\.completed).map(\.description) -> let descriptions2 = toDoList.filter { $0.completed }.map { $0.description } @@ -2019,7 +2019,7 @@ let someTask = toDoList[keyPath: taskKeyPath] <- Made an index >> print(type(of: taskKeyPath)) << WritableKeyPath, Task> - --- + // Using taskKeyPath doesn't call makeIndex() again. -> let someTask = toDoList[keyPath: taskKeyPath] ``` @@ -2081,10 +2081,10 @@ let selectorForPropertyGetter = #selector(getter: SomeClass.property) >> import Foundation -> class SomeClass: NSObject { -> @objc let property: String - --- + -> @objc(doSomethingWithInt:) func doSomething(_ x: Int) { } - --- + init(property: String) { self.property = property } @@ -2201,10 +2201,10 @@ if let value = c.value(forKey: keyPath) { self.someProperty = someProperty } } - --- + -> let c = SomeClass(someProperty: 12) -> let keyPath = #keyPath(SomeClass.someProperty) - --- + -> if let value = c.value(forKey: keyPath) { -> print(value) -> } @@ -2342,7 +2342,7 @@ anotherFunction(x: x) { $0 == 13 } g: { print(99) } >> let r1 = -> someFunction(x: x) { $0 == 13 } >> assert(r1 == false) - --- + >> func anotherFunction(x: Int, f: (Int) -> Bool, g: () -> Void) -> Bool { >> g(); return f(x) >> } @@ -2445,7 +2445,7 @@ the closure is wrapped in `Optional` automatically. ```swifttest // These tests match the example types given above // when describing what "structurally resembles" a function type. - --- + >> func f1(x: Int, y: (Bool)->Int) { print(x + y(true)) } >> f1(x: 10) { $0 ? 1 : 100 } << 11 @@ -2497,7 +2497,7 @@ someFunction { return $0 } secondClosure: { return $0 } // Prints "10 20" let second = secondClosure?(20) print(first ?? "-", second ?? "-") } - --- + -> someFunction() // Prints "- -" << - - -> someFunction { return $0 + 100 } // Ambiguous @@ -2564,7 +2564,7 @@ withUnsafePointer(to: myNumber) { unsafeFunction(pointer: $0) } >> print(pointer.pointee) -> } -> var myNumber = 1234 - --- + -> unsafeFunction(pointer: &myNumber) -> withUnsafePointer(to: myNumber) { unsafeFunction(pointer: $0) } << 1234 @@ -2608,24 +2608,24 @@ avoid using `&` instead of using the unsafe APIs explicitly. >> var nsarray: NSArray = [10, 20, 30] >> var bridgedNSArray = nsarray as! Array >> var string = "Hello" - --- + // bullet 1 >> takesUnsafePointer(p: &n) >> takesUnsafeMutablePointer(p: &n) - --- + // bullet 2 >> takesUnsafePointer(p: &array) >> takesUnsafeMutablePointer(p: &array) >> takesUnsafePointer(p: &bridgedNSArray) >> takesUnsafeMutablePointer(p: &bridgedNSArray) - --- + // bullet 3 >> takesUnsafePointer(p: array) >> takesUnsafePointer(p: bridgedNSArray) - --- + // bullet 4 >> takesUnsafePointerCChar(p: string) - --- + // invalid conversions >> takesUnsafeMutablePointer(p: array) !$ error: cannot convert value of type '[Int]' to expected argument type 'UnsafeMutablePointer' @@ -2734,7 +2734,7 @@ let s4 = type(of: someValue)(data: 5) // Error >> } -> let s1 = SomeType.init(data: 3) // Valid -> let s2 = SomeType(data: 1) // Also valid - --- + >> let someValue = s1 -> let s3 = type(of: someValue).init(data: 7) // Valid -> let s4 = type(of: someValue)(data: 5) // Error @@ -2850,7 +2850,7 @@ let d: (Int, Bool) -> Void = instance.overloadedMethod(x:y:) // Unambiguous func overloadedMethod(x: Int, y: Bool) {} } -> let instance = SomeClass() - --- + -> let a = instance.someMethod // Ambiguous !$ error: ambiguous use of 'someMethod' !! let a = instance.someMethod // Ambiguous @@ -2862,7 +2862,7 @@ let d: (Int, Bool) -> Void = instance.overloadedMethod(x:y:) // Unambiguous !! func someMethod(x: Int, z: Int) {} !! ^ -> let b = instance.someMethod(x:y:) // Unambiguous - --- + -> let d = instance.overloadedMethod // Ambiguous !$ error: ambiguous use of 'overloadedMethod(x:y:)' !! let d = instance.overloadedMethod // Ambiguous @@ -3139,7 +3139,7 @@ someDictionary["a"]![0] = 100 -> x! += 1 /> x is now \(x!) var someDictionary = ["a": [1, 2, 3], "b": [10, 20]] -> someDictionary["a"]![0] = 100 /> someDictionary is now \(someDictionary) @@ -3258,12 +3258,12 @@ someDictionary["a"]?[0] = someFunctionWithSideEffects() return 42 // No actual side effects. } -> var someDictionary = ["a": [1, 2, 3], "b": [10, 20]] - --- + -> someDictionary["not here"]?[0] = someFunctionWithSideEffects() // someFunctionWithSideEffects isn't evaluated /> someDictionary is still \(someDictionary) someDictionary["a"]?[0] = someFunctionWithSideEffects() /> someFunctionWithSideEffects is evaluated and returns \(someFunctionWithSideEffects()) > protocol SomeProtocol { } >> extension Bool: SomeProtocol { } - --- + >> extension Collection where Element: SomeProtocol { >> func returnTrue() -> Bool where Element == Bool { >> return true diff --git a/TSPL.docc/ReferenceManual/Patterns.md b/TSPL.docc/ReferenceManual/Patterns.md index 4c3d5a8f8..bc0fcd529 100644 --- a/TSPL.docc/ReferenceManual/Patterns.md +++ b/TSPL.docc/ReferenceManual/Patterns.md @@ -328,7 +328,7 @@ if case let x? = someOptional { print(x) } << 42 - --- + -> // Match using an optional pattern. -> if case let x? = someOptional { print(x) diff --git a/TSPL.docc/ReferenceManual/Statements.md b/TSPL.docc/ReferenceManual/Statements.md index 705568981..96af6245e 100644 --- a/TSPL.docc/ReferenceManual/Statements.md +++ b/TSPL.docc/ReferenceManual/Statements.md @@ -1118,7 +1118,7 @@ otherwise, it returns `false`. >> #else >> #error("Can't import A") >> #endif - --- + >> #if canImport(canImport_A.B) >> #else >> #error("Can't import A.B") diff --git a/TSPL.docc/ReferenceManual/Types.md b/TSPL.docc/ReferenceManual/Types.md index 94e44525f..2c41b6d80 100644 --- a/TSPL.docc/ReferenceManual/Types.md +++ b/TSPL.docc/ReferenceManual/Types.md @@ -249,7 +249,7 @@ For example: -> func someFunction(left: Int, right: Int) {} -> func anotherFunction(left: Int, right: Int) {} -> func functionWithDifferentLabels(top: Int, bottom: Int) {} - --- + -> var f = someFunction // The type of f is (Int, Int) -> Void, not (left: Int, right: Int) -> Void. >> print(type(of: f)) << (Int, Int) -> () @@ -281,17 +281,17 @@ f = functionWithDifferentNumberOfArguments // Error -> func someFunction(left: Int, right: Int) {} -> func anotherFunction(left: Int, right: Int) {} -> func functionWithDifferentLabels(top: Int, bottom: Int) {} - --- + -> var f = someFunction // The type of f is (Int, Int) -> Void, not (left: Int, right: Int) -> Void. -> f = anotherFunction // OK -> f = functionWithDifferentLabels // OK - --- + -> func functionWithDifferentArgumentTypes(left: Int, right: String) {} -> f = functionWithDifferentArgumentTypes // Error !$ error: cannot assign value of type '(Int, String) -> ()' to type '(Int, Int) -> ()' !! f = functionWithDifferentArgumentTypes // Error !! ^ - --- + -> func functionWithDifferentNumberOfArguments(left: Int, right: Int, top: Int) {} -> f = functionWithDifferentNumberOfArguments // Error !$ error: type of expression is ambiguous without more context @@ -406,11 +406,11 @@ see . >> } >> return g >> } - --- + >> let a: (Int) -> (Int) -> Int = f >> let r0 = a(3)(5) >> assert(r0 == 8) - --- + >> let b: (Int) -> ((Int) -> Int) = f >> let r1 = b(3)(5) >> assert(r1 == 8) @@ -1242,12 +1242,12 @@ print(type(of: z.f())) -> let x = Superclass() -> print(type(of: x.f())) <- Superclass - --- + -> class Subclass: Superclass { } -> let y = Subclass() -> print(type(of: y.f())) <- Subclass - --- + -> let z: Superclass = Subclass() -> print(type(of: z.f())) <- Subclass