### Initialize Dictionary and Array for map() Example Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/Closures.md Sets up a dictionary for digit-to-name mapping and an array of integers. These are prerequisites for the subsequent `map` operation example. ```swift let digitNames = [ 0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four", 5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine" ] let numbers = [16, 58, 510] ``` -------------------------------- ### Initialize Snakes and Ladders game state Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/ControlFlow.md Setup variables and the board array for the Snakes and Ladders game example. ```swift let finalSquare = 25 var board = [Int](repeating: 0, count: finalSquare + 1) board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02 board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08 var square = 0 var diceRoll = 0 ``` -------------------------------- ### Comment Formatting Examples Source: https://github.com/swiftlang/swift-book/blob/main/Style.md Examples of how to format comments for print statements and code evaluation status. ```text // Prints "The first item, 'one', is a string." // Prints "Job sent". ``` ```text // OK: Evaluates to true. // Error: Value consumed more than once. ``` -------------------------------- ### Swift Read and Write Memory Access Example Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/MemorySafety.md This example demonstrates a basic write access to a variable followed by a read access. Swift ensures these operations are safe by default. ```swift // 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)!") ``` -------------------------------- ### Example of nested macro usage Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/Macros.md Demonstrates the syntax for nesting macros within declarations. ```swift let something = #someMacro { struct A { } @someMacro struct B { } } ``` -------------------------------- ### Creating Selectors for Methods and Properties Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/ReferenceManual/Expressions.md Example of creating selectors for a class method and a property getter. ```swift class SomeClass: NSObject { @objc let property: String @objc(doSomethingWithInt:) func doSomething(_ x: Int) { } init(property: String) { self.property = property } } let selectorForMethod = #selector(SomeClass.doSomething(_:)) let selectorForPropertyGetter = #selector(getter: SomeClass.property) ``` -------------------------------- ### Tuple Comparison Example Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/BasicOperators.md Demonstrates a valid tuple comparison operation in Swift. ```swift let x = ("blue", -1) < ("purple", 1) // OK, evaluates to true print(x) ``` -------------------------------- ### StepCounter Implementation Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/Properties.md A practical example using willSet and didSet to track and report changes to a step count. ```swift class StepCounter { var totalSteps: Int = 0 { willSet(newTotalSteps) { print("About to set totalSteps to \(newTotalSteps)") } didSet { if totalSteps > oldValue { print("Added \(totalSteps - oldValue) steps") } } } } let stepCounter = StepCounter() stepCounter.totalSteps = 200 // About to set totalSteps to 200 // Added 200 steps stepCounter.totalSteps = 360 ``` -------------------------------- ### Configure Package.swift for Macros Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/Macros.md Initial setup for a Package.swift file to support macro development, requiring Swift 5.9+ and CompilerPluginSupport. ```swift // swift-tools-version: 5.9 import PackageDescription import CompilerPluginSupport let package = Package( name: "MyPackage", platforms: [ .iOS(.v17), .macOS(.v13)], // ... ) ``` -------------------------------- ### Swift Function Parameter Syntax Examples Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/ReferenceManual/Declarations.md Illustrates the syntax for ignored, variadic, and default value parameters in Swift functions. ```swift _ : <#parameter type#> ``` ```swift <#parameter name#>: <#parameter type#>... ``` ```swift <#parameter name#>: <#parameter type#> = <#default argument value#> ``` -------------------------------- ### Use Counter with TowardsZeroSource Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/Protocols.md Demonstrates using the TowardsZeroSource to count towards zero from a negative starting value. ```swift counter.count = -4 counter.dataSource = TowardsZeroSource() for _ in 1...5 { counter.increment() print(counter.count) } // -3 // -2 // -1 // 0 // 0 ``` -------------------------------- ### Instantaneous Memory Access Example in Swift Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/MemorySafety.md This code demonstrates typical instantaneous memory accesses. Most memory operations are instantaneous by nature. ```swift func oneMore(than number: Int) -> Int { return number + 1 } var myNumber = 1 myNumber = oneMore(than: myNumber) print(myNumber) // Prints "2". ``` -------------------------------- ### Define Supporting Structures Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/Extensions.md Define basic structures with default property values for use in examples. ```swift struct Size { var width = 0.0, height = 0.0 } struct Point { var x = 0.0, y = 0.0 } struct Rect { var origin = Point() var size = Size() } ``` -------------------------------- ### Create and Use Generic Stack of Strings Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/Generics.md Example of creating a new Stack instance for String values and using its push method. ```swift var stackOfStrings = Stack() stackOfStrings.push("uno") stackOfStrings.push("dos") stackOfStrings.push("tres") stackOfStrings.push("cuatro") ``` -------------------------------- ### Define Resolution and VideoMode Types Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/ClassesAndStructures.md Example of defining a structure with stored properties and a class with multiple property types. ```swift struct Resolution { var width = 0 var height = 0 } class VideoMode { var resolution = Resolution() var interlaced = false var frameRate = 0.0 var name: String? } ``` -------------------------------- ### Satisfy Failable Initializer Requirements Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/Protocols.md Examples of how failable and nonfailable initializers satisfy protocol requirements. ```swifttest -> protocol P { init?(i: Int) } -> class C: P { required init?(i: Int) {} } -> struct S: P { init?(i: Int) {} } ``` ```swifttest -> protocol P { init?(i: Int) } -> class C: P { required init!(i: Int) {} } -> struct S: P { init!(i: Int) {} } ``` ```swifttest -> protocol P { init!(i: Int) } -> class C: P { required init?(i: Int) {} } -> struct S: P { init?(i: Int) {} } ``` ```swifttest -> protocol P { init!(i: Int) } -> class C: P { required init!(i: Int) {} } -> struct S: P { init!(i: Int) {} } ``` ```swifttest -> protocol P { init?(i: Int) } -> class C: P { required init(i: Int) {} } -> struct S: P { init(i: Int) {} } ``` ```swifttest -> protocol P { init!(i: Int) } -> class C: P { required init(i: Int) {} } -> struct S: P { init(i: Int) {} } ``` ```swifttest -> protocol P { init(i: Int) } -> class C: P { required init(i: Int) {} } -> struct S: P { init(i: Int) {} } ``` ```swifttest -> protocol P { init(i: Int) } -> class C: P { required init!(i: Int) {} } -> struct S: P { init!(i: Int) {} } ``` -------------------------------- ### Initialize Food instances Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/Initialization.md Demonstrates creating Food instances using both the designated and convenience initializers. ```swift let namedMeat = Food(name: "Bacon") // namedMeat's name is "Bacon" ``` ```swift let mysteryMeat = Food() // mysteryMeat's name is "[Unnamed]" ``` -------------------------------- ### Iterate Over Array with Index and Value in Swift Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/CollectionTypes.md Use the `enumerated()` method with a `for-in` loop to iterate over an array, getting both the index and the value of each element. Indices start at 0. ```swift for (index, value) in shoppingList.enumerated() { print("Item \(index + 1): \(value)") } // Item 1: Six eggs // Item 2: Milk // Item 3: Flour // Item 4: Baking Powder // Item 5: Bananas ``` -------------------------------- ### Initialize and Link Courses Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/AutomaticReferenceCounting.md Demonstrates creating a department and linking multiple courses using unowned optional references. ```swift 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] ``` -------------------------------- ### Macro Call Example Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/Macros.md A basic example of invoking the #fourCharacterCode macro with a string literal. ```swift let magicNumber = #fourCharacterCode("ABCD") ``` -------------------------------- ### Print "Hello, world!" in Swift Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/GuidedTour/GuidedTour.md This is a complete Swift program. Code at global scope serves as the entry point, eliminating the need for a `main()` function. Semicolons are optional. ```swift print("Hello, world!") // Prints "Hello, world!" ``` -------------------------------- ### Define Custom Operators with Dots Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/ReferenceManual/LexicalStructure.md Custom operators starting with a dot can contain additional dots, while those not starting with a dot cannot contain them. ```swift infix operator .+ infix operator .+. ``` -------------------------------- ### Create ShoppingListItem Instances and Print Descriptions Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/Initialization.md Shows how to create ShoppingListItem instances using inherited initializers and then modify their properties. It demonstrates printing the computed description for each item. ```swift var breakfastList = [ ShoppingListItem(), ShoppingListItem(name: "Bacon"), ShoppingListItem(name: "Eggs", quantity: 6), ] breakfastList[0].name = "Orange juice" breakfastList[0].purchased = true for item in breakfastList { print(item.description) } ``` -------------------------------- ### Property Requirements in Swift Protocols Source: https://github.com/swiftlang/swift-book/blob/main/bin/redirects/ReferenceManual/Expressions.html Protocols can require that conforming types have specific properties. These can be read-only (`{ get }`) or read-write (`{ get set }`). ```swift protocol FullyNamed { var fullName: String { get } } struct PersonStruct: FullyNamed { var name: String var fullName: String { return name } } class Starship: FullyNamed { var name: String init(name: String) { self.name = name } var fullName: String { return name } } ``` -------------------------------- ### Instantiate and Interact with Player and Bank Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/Deinitialization.md This example demonstrates creating a Player instance, printing their initial coins and the remaining bank balance. It shows how player actions affect the bank's state. ```swift var playerOne: Player? = Player(coins: 100) print("A new player has joined the game with \(playerOne!.coinsInPurse) coins") // Prints "A new player has joined the game with 100 coins". print("There are now \(Bank.coinsInBank) coins left in the bank") // Prints "There are now 9900 coins left in the bank". ``` -------------------------------- ### Initialize and Link Instances Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/AutomaticReferenceCounting.md Creates a Customer instance and assigns a new CreditCard instance to its card property. ```swift john = Customer(name: "John Appleseed") john!.card = CreditCard(number: 1234_5678_9012_3456, customer: john!) ``` -------------------------------- ### Create and Use Class Instances Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/GuidedTour/GuidedTour.md Instantiate a class by calling its name followed by parentheses. Access properties and methods using dot syntax. ```swift var shape = Shape() shape.numberOfSides = 7 var shapeDescription = shape.simpleDescription() ``` -------------------------------- ### Property Requirements in Swift Protocols Source: https://github.com/swiftlang/swift-book/blob/main/bin/redirects/GuidedTour/GuidedTour.html Protocols can require specific properties to be implemented. Specify `get` for read-only and `get set` for read-write properties. ```swift protocol FullyNamed { var fullName: String { get } } ``` -------------------------------- ### Creating and Initializing AudioChannel Instances in Swift Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/Properties.md Shows how to create instances of the `AudioChannel` structure to represent individual audio channels, such as for a stereo system. This sets up the basic objects for managing audio levels. ```swift var leftChannel = AudioChannel() var rightChannel = AudioChannel() ``` -------------------------------- ### Property Requirements in Swift Protocols Source: https://github.com/swiftlang/swift-book/blob/main/bin/redirects/LanguageGuide/CollectionTypes.html Specify properties that conforming types must have. You can require properties to be readable (`get`), or both readable and writable (`get set`). ```swift protocol FullyNamed { var fullName: String { get } } struct Person: FullyNamed { var fullName: String } ``` -------------------------------- ### Property Requirements in Swift Protocols Source: https://github.com/swiftlang/swift-book/blob/main/bin/redirects/LanguageGuide/ControlFlow.html Protocols can require specific properties to be implemented by conforming types. Specify the property name, type, and whether it should be readable (`get`) or readable and writable (`get set`). ```swift var needsSizing: Bool { get } var name: String { get set } ``` -------------------------------- ### Create Rect Instances Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/Extensions.md Demonstrates creating instances of the Rect structure using its default and memberwise initializers. ```swift let defaultRect = Rect() let memberwiseRect = Rect(origin: Point(x: 2.0, y: 2.0), size: Size(width: 5.0, height: 5.0)) ``` -------------------------------- ### Count Scenes in Act 1 Using hasPrefix Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/StringsAndCharacters.md Counts the number of scenes in Act 1 of Romeo and Juliet by iterating through an array of scene strings and checking if each string starts with 'Act 1 '. This method is efficient for filtering based on a common starting pattern. ```swift let romeoAndJuliet = [ "Act 1 Scene 1: Verona, A public place", "Act 1 Scene 2: Capulet's mansion", "Act 1 Scene 3: A room in Capulet's mansion", "Act 1 Scene 4: A street outside Capulet's mansion", "Act 1 Scene 5: The Great Hall in Capulet's mansion", "Act 2 Scene 1: Outside Capulet's mansion", "Act 2 Scene 2: Capulet's orchard", "Act 2 Scene 3: Outside Friar Lawrence's cell", "Act 2 Scene 4: A street in Verona", "Act 2 Scene 5: Capulet's mansion", "Act 2 Scene 6: Friar Lawrence's cell" ] var act1SceneCount = 0 for scene in romeoAndJuliet { if scene.hasPrefix("Act 1 ") { act1SceneCount += 1 } } print("There are \(act1SceneCount) scenes in Act 1") ``` -------------------------------- ### Define and Initialize Property Wrappers Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/ReferenceManual/Attributes.md Defines a wrapper with multiple initializers and demonstrates different ways to apply it to properties. ```swift @propertyWrapper struct SomeWrapper { var wrappedValue: Int var someValue: Double init() { self.wrappedValue = 100 self.someValue = 12.3 } init(wrappedValue: Int) { self.wrappedValue = wrappedValue self.someValue = 45.6 } init(wrappedValue value: Int, custom: Double) { self.wrappedValue = value 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 } ``` -------------------------------- ### Default Initializers for Structs and Classes Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/Initialization.md Demonstrates the creation of instances using default initializers for structures and classes with default property values. ```swifttest -> struct S { var s: String = "s" } -> assert(S().s == "s") -> class A { var a: String = "a" } -> assert(A().a == "a") -> class B: A { var b: String = "b" } -> assert(B().a == "a") -> assert(B().b == "b") ``` -------------------------------- ### Create and Link Person and Apartment Instances Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/AutomaticReferenceCounting.md Creates instances of Person and Apartment and establishes links between them, including a weak reference from Apartment to Person. This setup is used to demonstrate weak reference behavior. ```swift var john: Person? var unit4A: Apartment? john = Person(name: "John Appleseed") unit4A = Apartment(unit: "4A") john!.apartment = unit4A unit4A!.tenant = john ``` -------------------------------- ### Actor Isolation Example Source: https://github.com/swiftlang/swift-book/blob/main/Style.md Demonstrates how to annotate types and variables isolated to a global actor. ```swift @MainActor struct MyType { ... } let m: MyType ``` -------------------------------- ### Create Color Instances Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/Initialization.md Demonstrates creating instances of the Color structure using its defined initializers. Use the `red:green:blue:` label for RGB initialization and `white:` for grayscale. ```swift let magenta = Color(red: 1.0, green: 0.0, blue: 1.0) let halfGray = Color(white: 0.5) ``` -------------------------------- ### Counting Characters in Swift Source: https://github.com/swiftlang/swift-book/blob/main/bin/redirects/ReferenceManual/Expressions.html Get the number of characters in a string using its `count` property. ```swift let unusualPoem = "\u{1F4A9}\u{1F5A4}\u{FE0F}\u{1F51D}" print("The number of characters in \(unusualPoem) is \(unusualPoem.count)") ``` -------------------------------- ### Counting Characters in Swift Source: https://github.com/swiftlang/swift-book/blob/main/bin/redirects/LanguageGuide/TypeCasting.html Get the number of characters in a string using the `count` property. ```swift let unusualHowLong = "patience" print("\(unusualHowLong.count) characters") ``` -------------------------------- ### Property Wrapper with Custom Initializer Arguments Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/Properties.md Shows how to provide arguments to a property wrapper's initializer to set initial values and constraints. ```swift struct NarrowRectangle { @SmallNumber(wrappedValue: 2, maximum: 5) var height: Int @SmallNumber(wrappedValue: 3, maximum: 4) var width: Int } var narrowRectangle = NarrowRectangle() print(narrowRectangle.height, narrowRectangle.width) narrowRectangle.height = 100 narrowRectangle.width = 100 print(narrowRectangle.height, narrowRectangle.width) ``` -------------------------------- ### Conforming to Protocols with Different Access Levels in Swift Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/AccessControl.md Illustrates how classes with different access levels can conform to protocols of varying access levels. This example highlights which combinations are permissible and which result in compilation errors due to visibility constraints. ```swifttest // these should all be allowed without problem -> public class PublicClassConformingToPublicProtocol: PublicProtocol { public var publicProperty = 0 public func publicMethod() {} } -> internal class InternalClassConformingToPublicProtocol: PublicProtocol { var publicProperty = 0 func publicMethod() {} } -> private class PrivateClassConformingToPublicProtocol: PublicProtocol { var publicProperty = 0 func publicMethod() {} } -> public class PublicClassConformingToInternalProtocol: InternalProtocol { var internalProperty = 0 func internalMethod() {} } -> internal class InternalClassConformingToInternalProtocol: InternalProtocol { var internalProperty = 0 func internalMethod() {} } -> private class PrivateClassConformingToInternalProtocol: InternalProtocol { var internalProperty = 0 func internalMethod() {} } ``` ```swifttest // these will fail, because FilePrivateProtocol isn't visible outside of its file -> public class PublicClassConformingToFilePrivateProtocol: FilePrivateProtocol { var filePrivateProperty = 0 func filePrivateMethod() {} } !$ 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 func privateMethod() {} } !$ error: cannot find type 'PrivateProtocol' in scope !! public class PublicClassConformingToPrivateProtocol: PrivateProtocol { !! ^~~~~~~~~~~~~~ ``` -------------------------------- ### Counting Characters in Swift Source: https://github.com/swiftlang/swift-book/blob/main/bin/redirects/LanguageGuide/StringsAndCharacters.html Get the number of characters in a string using its `count` property. ```swift let unusualMenagerie = "No unicycler or pentacyclist were injured in the making of this story." print("\(unusualMenagerie.count) characters") ``` -------------------------------- ### Counting Characters in Swift Source: https://github.com/swiftlang/swift-book/blob/main/bin/redirects/LanguageGuide/Protocols.html Get the number of characters in a string using the `.count` property. ```swift let greeting = "G'day!" print(greeting.count) ``` -------------------------------- ### Counting Characters in Swift Source: https://github.com/swiftlang/swift-book/blob/main/bin/redirects/LanguageGuide/ControlFlow.html Get the number of characters in a string using the `.count` property. ```swift let greeting = "Guten Tag!" print("\(greeting.count) characters") ``` -------------------------------- ### Counting Characters in Swift Source: https://github.com/swiftlang/swift-book/blob/main/bin/redirects/LanguageGuide/BasicOperators.html Get the number of characters in a string using the `count` property. ```swift let unusualPoem = "\u{1F4A9}\u{1F4A9}\u{1F4A9}" print("\(unusualPoem.count) characters") ``` -------------------------------- ### Define a read-only subscript Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/Subscripts.md Simplify read-only subscripts by omitting the get keyword and its braces. ```swift subscript(index: Int) -> Int { // Return an appropriate subscript value here. } ``` -------------------------------- ### Create RecipeIngredient Instances Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/Initialization.md Demonstrates creating instances of RecipeIngredient using its convenience initializers. These initializers are inherited from its superclass and its own defined initializers. ```swift let oneMysteryItem = RecipeIngredient() let oneBacon = RecipeIngredient(name: "Bacon") let sixEggs = RecipeIngredient(name: "Eggs", quantity: 6) ``` -------------------------------- ### Define a protocol with inheritance Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/Protocols.md Example of a protocol that inherits from TextRepresentable and adds a new property requirement. ```swift protocol PrettyTextRepresentable: TextRepresentable { var prettyTextualDescription: String { get } } ``` -------------------------------- ### Initialize a VideoMode class instance Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/ClassesAndStructures.md Creates a new instance of the VideoMode class and assigns initial property values. ```swift let tenEighty = VideoMode() tenEighty.resolution = hd tenEighty.interlaced = true tenEighty.name = "1080i" tenEighty.frameRate = 25.0 ``` -------------------------------- ### Define a Protocol in Swift Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/GuidedTour/GuidedTour.md Use the `protocol` keyword to declare a protocol, specifying required properties and methods. This example defines `ExampleProtocol` with a read-only description and a mutating method. ```swift protocol ExampleProtocol { var simpleDescription: String { get } mutating func adjust() } ``` -------------------------------- ### Setting and Accessing Static Properties Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/Properties.md Demonstrates updating an instance property and observing the change in a shared static property. ```swift leftChannel.currentLevel = 7 print(leftChannel.currentLevel) // Prints "7". print(AudioChannel.maxInputLevelForAllChannels) // Prints "7". ``` ```swift rightChannel.currentLevel = 11 print(rightChannel.currentLevel) // Prints "10". print(AudioChannel.maxInputLevelForAllChannels) // Prints "10". ``` -------------------------------- ### Define a read-write subscript Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/Subscripts.md Use the subscript keyword with get and set blocks to define read-write access. ```swift subscript(index: Int) -> Int { get { // Return an appropriate subscript value here. } set(newValue) { // Perform a suitable setting action here. } } ``` -------------------------------- ### Assign Conditional Expression to Variable Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/ReferenceManual/Expressions.md Examples of assigning conditional expressions to variables with explicit type annotations or casts. ```swift let number: Double = if someCondition { 10 } else { 12.34 } let number = if someCondition { 10 as Double } else { 12.34 } ``` -------------------------------- ### Expand Property Wrapper to Manual Implementation Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/Properties.md Shows the manual implementation of a property wrapper using private storage and computed properties for access. ```swift struct SmallRectangle { private var _height = TwelveOrLess() private var _width = TwelveOrLess() var height: Int { get { return _height.wrappedValue } set { _height.wrappedValue = newValue } } var width: Int { get { return _width.wrappedValue } set { _width.wrappedValue = newValue } } } ``` -------------------------------- ### Implement a read-only TimesTable subscript Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/Subscripts.md A practical example of a read-only subscript used to calculate values based on a multiplier. ```swift struct TimesTable { let multiplier: Int subscript(index: Int) -> Int { return multiplier * index } } let threeTimesTable = TimesTable(multiplier: 3) print("six times three is \(threeTimesTable[6])") // Prints "six times three is 18". ``` -------------------------------- ### Define and Use a Function Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/GuidedTour/GuidedTour.md Demonstrates defining a function and passing it as an argument to another function. ```swift func lessThanTen(number: Int) -> Bool { return number < 10 } -> var numbers = [20, 19, 7, 12] >> let anyMatches = -> hasAnyMatches(list: numbers, condition: lessThanTen) >> print(anyMatches) << true ``` -------------------------------- ### Adopt Semantic Protocols Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/Protocols.md Demonstrates adopting protocols that have no required methods or properties. ```swift struct MyStruct: Copyable { var counter = 12 } extension MyStruct: BitwiseCopyable { } ``` -------------------------------- ### Prefix and Suffix Equality in Swift Source: https://github.com/swiftlang/swift-book/blob/main/bin/redirects/LanguageGuide/Protocols.html Check if a string starts or ends with a specific substring using `hasPrefix(_:)` and `hasSuffix(_:)`. ```swift let quote = "To be or not to be" quote.hasPrefix("To be") quote.hasSuffix("not to be") ``` -------------------------------- ### Prefix and Suffix Equality in Swift Source: https://github.com/swiftlang/swift-book/blob/main/bin/redirects/LanguageGuide/Extensions.html Check if a string starts or ends with a specific substring using `hasPrefix()` and `hasSuffix()`. ```swift let السيارة = "🚗" let ama = "I love cars" let start = ama.hasPrefix("I love") let end = ama.hasSuffix("cars") ``` -------------------------------- ### Instantiate and Use Overridden Property in Swift Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/Inheritance.md Demonstrates creating an instance of a subclass with overridden properties and printing the customized description. ```swift let car = Car() car.currentSpeed = 25.0 car.gear = 3 print("Car: \(car.description)") // Car: traveling at 25.0 miles per hour in gear 3 ``` -------------------------------- ### Define Macro Plugin Entry Point Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/Macros.md Create the main entry point for the macro target to register available macros. ```swift import SwiftCompilerPlugin @main struct MyProjectMacros: CompilerPlugin { var providingMacros: [Macro.Type] = [FourCharacterCode.self] } ``` -------------------------------- ### Counting Characters in Swift Strings Source: https://github.com/swiftlang/swift-book/blob/main/bin/redirects/GuidedTour/GuidedTour.html Get the number of extended grapheme clusters in a string using the `count` property. ```swift let name = "Alfred" print("\(name.count) characters") ``` -------------------------------- ### Instantiate and Use Overridden Property Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/Inheritance.md Demonstrates setting an overridden property and observing the resulting state change. ```swift let automatic = AutomaticCar() automatic.currentSpeed = 35.0 print("AutomaticCar: \(automatic.description)") // AutomaticCar: traveling at 35.0 miles per hour in gear 4 ``` -------------------------------- ### Get Dictionary Count in Swift Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/CollectionTypes.md Use the `count` property to find the number of items in a dictionary. This is a read-only property. ```swift print("The airports dictionary contains \(airports.count) items.") ``` -------------------------------- ### Get Array Count in Swift Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/CollectionTypes.md Use the `count` property to determine the number of items in an array. This is a read-only property. ```swift print("The shopping list contains \(shoppingList.count) items.") ``` -------------------------------- ### Protocol Composition in Swift Source: https://github.com/swiftlang/swift-book/blob/main/bin/redirects/ReferenceManual/Expressions.html Combine multiple protocols into a single requirement. Use `&` to combine protocols. For example, `TextRepresentable & PrettyPrinted`. ```swift func printIfPrettyPrinted(item: TextRepresentable & PrettyPrinted) { print("Item is pretty printed: \(item.textualDescription)") item.prettyPrint() } printIfPrettyPrinted(item: prettyPoint) ``` -------------------------------- ### Instantiate Structures and Classes Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/ClassesAndStructures.md Creating new instances of defined types using initializer syntax with empty parentheses. ```swift let someResolution = Resolution() let someVideoMode = VideoMode() ``` -------------------------------- ### Required Convenience Initializer Enforcement Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/Initialization.md This example shows a compile-time error when a subclass does not implement a required convenience initializer from its superclass. ```swift class C { init() {} required convenience init(i: Int) { self.init() } } class D: C { init(s: String) {} } ``` -------------------------------- ### Call instance methods using dot syntax Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/LanguageGuide/Methods.md Demonstrates invoking instance methods on a Counter object. ```swift let counter = Counter() // the initial counter value is 0 counter.increment() // the counter's value is now 1 counter.increment(by: 5) // the counter's value is now 6 counter.reset() // the counter's value is now 0 ``` -------------------------------- ### Swift Result Builder: buildEither Example Source: https://github.com/swiftlang/swift-book/blob/main/TSPL.docc/ReferenceManual/Attributes.md Demonstrates the use of buildEither for handling conditional logic within a result builder. ```swift static func buildEither(first: First) -> DrawEither { return DrawEither(content: first) } static func buildEither(second: Second) -> DrawEither { return DrawEither(content: second) } ```