Preload Assets in visionOS

TODO: collapasable, copyable, download, etc

How do you preload assets? Spatial computing goes even further with visionOS updates that bring enhanced support for volumetric apps, powerful new enterprise APIs, the new TabletopKit framework, and more.

visionOS Highlights

TabletopKit Create collaborative experiences centered around a table. This new framework handles the manipulation of cards and pieces, establishing placement and layout, and defining game boards.

New enterprise APIs provide access to spatial barcode scanning, the Apple Neural Engine, object tracking parameters, and more.

visionOS for enterprise

Volumetric APIs • Create apps that take full advantage of depth and space — and can

run side by side with other apps in the Shared Space.
• Resize volumes by using the SwiftUI scene

modifier windowResizability.

Decide if you want the user’s hands to appear in front of or behind your digital content.

Inputs

Getting started? Explore the visionOS Pathway on developer.apple.com 􀯻

• Detect planes in all orientations. • Allow anchoring objects on surfaces in your surroundings.
• Use Room Anchors to consider the user’s surroundings on a

per-room basis.
• Attach content to individual objects around the user with the new

Object Tracking API for visionOS.

Updates to scene understanding

URL: https://docs.swift.org/swift-book/documentation/the-swift-programming-language/thebasics The Swift Programming Language (6.0 beta) The Basics The Basics Work with common kinds of data and write basic syntax. Swift provides many fundamental data types, including Int for integers, Double for floating-point values, Bool for Boolean values, and String for text. Swift also provides powerful versions of the three primary collection types, Array, Set, and Dictionary, as described in Collection Types. Swift uses variables to store and refer to values by an identifying name. Swift also makes extensive use of variables whose values can’t be changed. These are known as constants, and are used throughout Swift to make code safer and clearer in intent when you work with values that don’t need to change. In addition to familiar types, Swift introduces advanced types such as tuples. Tuples enable you to create and pass around groupings of values. You can use a tuple to return multiple values from a function as a single compound value. Swift also introduces optional types, which handle the absence of a value. Optionals say either “there is a value, and it equals x” or “there isn’t a value at all”. Swift is a type-safe language, which means the language helps you to be clear about the types of values your code can work with. If part of your code requires a String, type safety prevents you from passing it an Int by mistake. Likewise, type safety prevents you from accidentally passing an optional String to a piece of code that requires a non-optional String. Type safety helps you catch and fix errors as early as possible in the development process. Constants and Variables Constants and variables associate a name (such as maximumNumberOfLoginAttempts or welcomeMessage) with a value of a particular type (such as the number 10 or the string "Hello"). The value of a constant can’t be changed once it’s set, whereas a variable can be set to a different value in the future. Declaring Constants and Variables Constants and variables must be declared before they’re used. You declare constants with the let keyword and variables with the var keyword. Here’s an example of how constants and variables can be used to track the number of login attempts a user has made: let maximumNumberOfLoginAttempts = 10 var currentLoginAttempt = 0 This code can be read as: “Declare a new constant called maximumNumberOfLoginAttempts, and give it a value of 10. Then, declare a new variable called currentLoginAttempt, and give it an initial value of 0.” In this example, the maximum number of allowed login attempts is declared as a constant, because the maximum value never changes. The current login attempt counter is declared as a variable, because this value must be incremented after each failed login attempt. If a stored value in your code won’t change, always declare it as a constant with the let keyword. Use variables only for storing values that change. When you declare a constant or a variable, you can give it a value as part of that declaration, like the examples above. Alternatively, you can assign its initial value later in the program, as long as it’s guaranteed to have a value before the first time you read from it. var environment = "development" let maximumNumberOfLoginAttempts: Int // maximumNumberOfLoginAttempts has no value yet.

if environment == "development" { maximumNumberOfLoginAttempts = 100 } else { maximumNumberOfLoginAttempts = 10 } // Now maximumNumberOfLoginAttempts has a value, and can be read. In this example, the maximum number of login attempts is constant, and its value depends on the environment. In the development environment, it has a value of 100; in any other environment, its value is 10. Both branches of the if statement initialize maximumNumberOfLoginAttempts with some value, guaranteeing that the constant always gets a value. For information about how Swift checks your code when you set an initial value this way, see Constant Declaration. You can declare multiple constants or multiple variables on a single line, separated by commas: var x = 0.0, y = 0.0, z = 0.0 Type Annotations You can provide a type annotation when you declare a constant or variable, to be clear about the kind of values the constant or variable can store. Write a type annotation by placing a colon after the constant or variable name, followed by a space, followed by the name of the type to use. This example provides a type annotation for a variable called welcomeMessage, to indicate that the variable can store String values: var welcomeMessage: String The colon in the declaration means “…of type…,” so the code above can be read as: “Declare a variable called welcomeMessage that’s of type String.” The phrase “of type String” means “can store any String value.” Think of it as meaning “the type of thing” (or “the kind of thing”) that can be stored. The welcomeMessage variable can now be set to any string value without error: welcomeMessage = "Hello" You can define multiple related variables of the same type on a single line, separated by commas, with a single type annotation after the final variable name: var red, green, blue: Double Note It’s rare that you need to write type annotations in practice. If you provide an initial value for a constant or variable at the point that it’s defined, Swift can almost always infer the type to be used for that constant or variable, as described in Type Safety and Type Inference. In the welcomeMessage example above, no initial value is provided, and so the type of the welcomeMessage variable is specified with a type annotation rather than being inferred from an initial value. Naming Constants and Variables Constant and variable names can contain almost any character, including Unicode characters: let π = 3.14159 let 你好 = "你好世界" let 🐶🐮 = "dogcow" Constant and variable names can’t contain whitespace characters, mathematical symbols, arrows, private-use Unicode scalar values, or line- and box-drawing characters. Nor can they begin with a number, although numbers may be included elsewhere within the name. Once you’ve declared a constant or variable of a certain type, you can’t declare it again with the same name, or change it to store values of a different type. Nor can you change a constant into a variable or a variable into a constant. Note If you need to give a constant or variable the same name as a reserved Swift keyword, surround the keyword with backticks (`) when using it as a name. However, avoid using keywords as names unless you have absolutely no choice. You can change the value of an existing variable to another value of a compatible type. In this example, the value of friendlyWelcome is changed from "Hello!" to "Bonjour!": var friendlyWelcome = "Hello!" friendlyWelcome = "Bonjour!" // friendlyWelcome is now "Bonjour!" Unlike a variable, the value of a constant can’t be changed after it’s set. Attempting to do so is reported as an error when your code is compiled: let languageName = "Swift" languageName = "Swift++" // This is a compile-time error: languageName cannot be changed. Printing Constants and Variables You can print the current value of a constant or variable with the print(:separator:terminator:) function: print(friendlyWelcome) // Prints "Bonjour!" The print(:separator:terminator:) function is a global function that prints one or more values to an appropriate output. In Xcode, for example, the print(:separator:terminator:) function prints its output in Xcode’s “console” pane. The separator and terminator parameter have default values, so you can omit them when you call this function. By default, the function terminates the line it prints by adding a line break. To print a value without a line break after it, pass an empty string as the terminator — for example, print(someValue, terminator: ""). For information about parameters with default values, see Default Parameter Values. Swift uses string interpolation to include the name of a constant or variable as a placeholder in a longer string, and to prompt Swift to replace it with the current value of that constant or variable. Wrap the name in parentheses and escape it with a backslash before the opening parenthesis: print("The current value of friendlyWelcome is (friendlyWelcome)") // Prints "The current value of friendlyWelcome is Bonjour!" Note All options you can use with string interpolation are described in String Interpolation. Comments Use comments to include nonexecutable text in your code, as a note or reminder to yourself. Comments are ignored by the Swift compiler when your code is compiled. Comments in Swift are very similar to comments in C. Single-line comments begin with two forward-slashes (//): // This is a comment. Multiline comments start with a forward-slash followed by an asterisk (/) and end with an asterisk followed by a forward-slash (/): /* This is also a comment but is written over multiple lines. / Unlike multiline comments in C, multiline comments in Swift can be nested inside other multiline comments. You write nested comments by starting a multiline comment block and then starting a second multiline comment within the first block. The second block is then closed, followed by the first block: / This is the start of the first multiline comment. /* This is the second, nested multiline comment. */ This is the end of the first multiline comment. */ Nested multiline comments enable you to comment out large blocks of code quickly and easily, even if the code already contains multiline comments. Semicolons Unlike many other languages, Swift doesn’t require you to write a semicolon (;) after each statement in your code, although you can do so if you wish. However, semicolons are required if you want to write multiple separate statements on a single line: let cat = "🐱"; print(cat) // Prints "🐱" Integers Integers are whole numbers with no fractional component, such as 42 and -23. Integers are either signed (positive, zero, or negative) or unsigned (positive or zero). Swift provides signed and unsigned integers in 8, 16, 32, and 64 bit forms. These integers follow a naming convention similar to C, in that an 8-bit unsigned integer is of type UInt8, and a 32-bit signed integer is of type Int32. Like all types in Swift, these integer types have capitalized names. Integer Bounds You can access the minimum and maximum values of each integer type with its min and max properties: let minValue = UInt8.min // minValue is equal to 0, and is of type UInt8 let maxValue = UInt8.max // maxValue is equal to 255, and is of type UInt8 The values of these properties are of the appropriate-sized number type (such as UInt8 in the example above) and can therefore be used in expressions alongside other values of the same type. Int In most cases, you don’t need to pick a specific size of integer to use in your code. Swift provides an additional integer type, Int, which has the same size as the current platform’s native word size: On a 32-bit platform, Int is the same size as Int32. On a 64-bit platform, Int is the same size as Int64. Unless you need to work with a specific size of integer, always use Int for integer values in your code. This aids code consistency and interoperability. Even on 32-bit platforms, Int can store any value between -2,147,483,648 and 2,147,483,647, and is large enough for many integer ranges. UInt Swift also provides an unsigned integer type, UInt, which has the same size as the current platform’s native word size: On a 32-bit platform, UInt is the same size as UInt32. On a 64-bit platform, UInt is the same size as UInt64. Note Use UInt only when you specifically need an unsigned integer type with the same size as the platform’s native word size. If this isn’t the case, Int is preferred, even when the values to be stored are known to be nonnegative. A consistent use of Int for integer values aids code interoperability, avoids the need to convert between different number types, and matches integer type inference, as described in Type Safety and Type Inference. Floating-Point Numbers Floating-point numbers are numbers with a fractional component, such as 3.14159, 0.1, and -273.15. Floating-point types can represent a much wider range of values than integer types, and can store numbers that are much larger or smaller than can be stored in an Int. Swift provides two signed floating-point number types: Double represents a 64-bit floating-point number. Float represents a 32-bit floating-point number. Note Double has a precision of at least 15 decimal digits, whereas the precision of Float can be as little as 6 decimal digits. The appropriate floating-point type to use depends on the nature and range of values you need to work with in your code. In situations where either type would be appropriate, Double is preferred. Type Safety and Type Inference Swift is a type-safe language. A type safe language encourages you to be clear about the types of values your code can work with. If part of your code requires a String, you can’t pass it an Int by mistake. Because Swift is type safe, it performs type checks when compiling your code and flags any mismatched types as errors. This enables you to catch and fix errors as early as possible in the development process. Type-checking helps you avoid errors when you’re working with different types of values. However, this doesn’t mean that you have to specify the type of every constant and variable that you declare. If you don’t specify the type of value you need, Swift uses type inference to work out the appropriate type. Type inference enables a compiler to deduce the type of a particular expression automatically when it compiles your code, simply by examining the values you provide. Because of type inference, Swift requires far fewer type declarations than languages such as C or Objective-C. Constants and variables are still explicitly typed, but much of the work of specifying their type is done for you. Type inference is particularly useful when you declare a constant or variable with an initial value. This is often done by assigning a literal value (or literal) to the constant or variable at the point that you declare it. (A literal value is a value that appears directly in your source code, such as 42 and 3.14159 in the examples below.) For example, if you assign a literal value of 42 to a new constant without saying what type it is, Swift infers that you want the constant to be an Int, because you have initialized it with a number that looks like an integer: let meaningOfLife = 42 // meaningOfLife is inferred to be of type Int Likewise, if you don’t specify a type for a floating-point literal, Swift infers that you want to create a Double: let pi = 3.14159 // pi is inferred to be of type Double Swift always chooses Double (rather than Float) when inferring the type of floating-point numbers. If you combine integer and floating-point literals in an expression, a type of Double will be inferred from the context: let anotherPi = 3 + 0.14159 // anotherPi is also inferred to be of type Double The literal value of 3 has no explicit type in and of itself, and so an appropriate output type of Double is inferred from the presence of a floating-point literal as part of the addition. Numeric Literals Integer literals can be written as: A decimal number, with no prefix A binary number, with a 0b prefix An octal number, with a 0o prefix A hexadecimal number, with a 0x prefix All of these integer literals have a decimal value of 17: let decimalInteger = 17 let binaryInteger = 0b10001 // 17 in binary notation let octalInteger = 0o21 // 17 in octal notation let hexadecimalInteger = 0x11 // 17 in hexadecimal notation Floating-point literals can be decimal (with no prefix), or hexadecimal (with a 0x prefix). They must always have a number (or hexadecimal number) on both sides of the decimal point. Decimal floats can also have an optional exponent, indicated by an uppercase or lowercase e; hexadecimal floats must have an exponent, indicated by an uppercase or lowercase p. For decimal numbers with an exponent of x, the base number is multiplied by 10ˣ: 1.25e2 means 1.25 x 10², or 125.0. 1.25e-2 means 1.25 x 10⁻², or 0.0125. For hexadecimal numbers with an exponent of x, the base number is multiplied by 2ˣ: 0xFp2 means 15 x 2², or 60.0. 0xFp-2 means 15 x 2⁻², or 3.75. All of these floating-point literals have a decimal value of 12.1875: let decimalDouble = 12.1875 let exponentDouble = 1.21875e1 let hexadecimalDouble = 0xC.3p0 Numeric literals can contain extra formatting to make them easier to read. Both integers and floats can be padded with extra zeros and can contain underscores to help with readability. Neither type of formatting affects the underlying value of the literal: let paddedDouble = 000123.456 let oneMillion = 1_000_000 let justOverOneMillion = 1_000_000.000_000_1 Numeric Type Conversion Use the Int type for all general-purpose integer constants and variables in your code, even if they’re known to be nonnegative. Using the default integer type in everyday situations means that integer constants and variables are immediately interoperable in your code and will match the inferred type for integer literal values. Use other integer types only when they’re specifically needed for the task at hand, because of explicitly sized data from an external source, or for performance, memory usage, or other necessary optimization. Using explicitly sized types in these situations helps to catch any accidental value overflows and implicitly documents the nature of the data being used. Integer Conversion The range of numbers that can be stored in an integer constant or variable is different for each numeric type. An Int8 constant or variable can store numbers between -128 and 127, whereas a UInt8 constant or variable can store numbers between 0 and 255. A number that won’t fit into a constant or variable of a sized integer type is reported as an error when your code is compiled: let cannotBeNegative: UInt8 = -1 // UInt8 can't store negative numbers, and so this will report an error let tooBig: Int8 = Int8.max + 1 // Int8 can't store a number larger than its maximum value, // and so this will also report an error Because each numeric type can store a different range of values, you must opt in to numeric type conversion on a case-by-case basis. This opt-in approach prevents hidden conversion errors and helps make type conversion intentions explicit in your code. To convert one specific number type to another, you initialize a new number of the desired type with the existing value. In the example below, the constant twoThousand is of type UInt16, whereas the constant one is of type UInt8. They can’t be added together directly, because they’re not of the same type. Instead, this example calls UInt16(one) to create a new UInt16 initialized with the value of one, and uses this value in place of the original: let twoThousand: UInt16 = 2_000 let one: UInt8 = 1 let twoThousandAndOne = twoThousand + UInt16(one) Because both sides of the addition are now of type UInt16, the addition is allowed. The output constant (twoThousandAndOne) is inferred to be of type UInt16, because it’s the sum of two UInt16 values. SomeType(ofInitialValue) is the default way to call the initializer of a Swift type and pass in an initial value. Behind the scenes, UInt16 has an initializer that accepts a UInt8 value, and so this initializer is used to make a new UInt16 from an existing UInt8. You can’t pass in any type here, however — it has to be a type for which UInt16 provides an initializer. Extending existing types to provide initializers that accept new types (including your own type definitions) is covered in Extensions. Integer and Floating-Point Conversion Conversions between integer and floating-point numeric types must be made explicit: let three = 3 let pointOneFourOneFiveNine = 0.14159 let pi = Double(three) + pointOneFourOneFiveNine // pi equals 3.14159, and is inferred to be of type Double Here, the value of the constant three is used to create a new value of type Double, so that both sides of the addition are of the same type. Without this conversion in place, the addition would not be allowed. Floating-point to integer conversion must also be made explicit. An integer type can be initialized with a Double or Float value: let integerPi = Int(pi) // integerPi equals 3, and is inferred to be of type Int Floating-point values are always truncated when used to initialize a new integer value in this way. This means that 4.75 becomes 4, and -3.9 becomes -3. Note The rules for combining numeric constants and variables are different from the rules for numeric literals. The literal value 3 can be added directly to the literal value 0.14159, because number literals don’t have an explicit type in and of themselves. Their type is inferred only at the point that they’re evaluated by the compiler. Type Aliases Type aliases define an alternative name for an existing type. You define type aliases with the typealias keyword. Type aliases are useful when you want to refer to an existing type by a name that’s contextually more appropriate, such as when working with data of a specific size from an external source: typealias AudioSample = UInt16 Once you define a type alias, you can use the alias anywhere you might use the original name: var maxAmplitudeFound = AudioSample.min // maxAmplitudeFound is now 0 Here, AudioSample is defined as an alias for UInt16. Because it’s an alias, the call to AudioSample.min actually calls UInt16.min, which provides an initial value of 0 for the maxAmplitudeFound variable. Booleans Swift has a basic Boolean type, called Bool. Boolean values are referred to as logical, because they can only ever be true or false. Swift provides two Boolean constant values, true and false: let orangesAreOrange = true let turnipsAreDelicious = false The types of orangesAreOrange and turnipsAreDelicious have been inferred as Bool from the fact that they were initialized with Boolean literal values. As with Int and Double above, you don’t need to declare constants or variables as Bool if you set them to true or false as soon as you create them. Type inference helps make Swift code more concise and readable when it initializes constants or variables with other values whose type is already known. Boolean values are particularly useful when you work with conditional statements such as the if statement: if turnipsAreDelicious { print("Mmm, tasty turnips!") } else { print("Eww, turnips are horrible.") } // Prints "Eww, turnips are horrible." Conditional statements such as the if statement are covered in more detail in Control Flow. Swift’s type safety prevents non-Boolean values from being substituted for Bool. The following example reports a compile-time error: let i = 1 if i { // this example will not compile, and will report an error } However, the alternative example below is valid: let i = 1 if i == 1 { // this example will compile successfully } The result of the i == 1 comparison is of type Bool, and so this second example passes the type-check. Comparisons like i == 1 are discussed in Basic Operators. As with other examples of type safety in Swift, this approach avoids accidental errors and ensures that the intention of a particular section of code is always clear. Tuples Tuples group multiple values into a single compound value. The values within a tuple can be of any type and don’t have to be of the same type as each other. In this example, (404, "Not Found") is a tuple that describes an HTTP status code. An HTTP status code is a special value returned by a web server whenever you request a web page. A status code of 404 Not Found is returned if you request a webpage that doesn’t exist. let http404Error = (404, "Not Found") // http404Error is of type (Int, String), and equals (404, "Not Found") The (404, "Not Found") tuple groups together an Int and a String to give the HTTP status code two separate values: a number and a human-readable description. It can be described as “a tuple of type (Int, String)”. You can create tuples from any permutation of types, and they can contain as many different types as you like. There’s nothing stopping you from having a tuple of type (Int, Int, Int), or (String, Bool), or indeed any other permutation you require. You can decompose a tuple’s contents into separate constants or variables, which you then access as usual: let (statusCode, statusMessage) = http404Error print("The status code is (statusCode)") // Prints "The status code is 404" print("The status message is (statusMessage)") // Prints "The status message is Not Found" If you only need some of the tuple’s values, ignore parts of the tuple with an underscore () when you decompose the tuple: let (justTheStatusCode, _) = http404Error print("The status code is (justTheStatusCode)") // Prints "The status code is 404" Alternatively, access the individual element values in a tuple using index numbers starting at zero: print("The status code is (http404Error.0)") // Prints "The status code is 404" print("The status message is (http404Error.1)") // Prints "The status message is Not Found" You can name the individual elements in a tuple when the tuple is defined: let http200Status = (statusCode: 200, description: "OK") If you name the elements in a tuple, you can use the element names to access the values of those elements: print("The status code is (http200Status.statusCode)") // Prints "The status code is 200" print("The status message is (http200Status.description)") // Prints "The status message is OK" Tuples are particularly useful as the return values of functions. A function that tries to retrieve a web page might return the (Int, String) tuple type to describe the success or failure of the page retrieval. By returning a tuple with two distinct values, each of a different type, the function provides more useful information about its outcome than if it could only return a single value of a single type. For more information, see Functions with Multiple Return Values. Note Tuples are useful for simple groups of related values. They’re not suited to the creation of complex data structures. If your data structure is likely to be more complex, model it as a class or structure, rather than as a tuple. For more information, see Structures and Classes. Optionals You use optionals in situations where a value may be absent. An optional represents two possibilities: Either there is a value of a specified type, and you can unwrap the optional to access that value, or there isn’t a value at all. As an example of a value that might be missing, Swift’s Int type has an initializer that tries to convert a String value into an Int value. However, only some strings can be converted into integers. The string "123" can be converted into the numeric value 123, but the string "hello, world" doesn’t have a corresponding numeric value. The example below uses the initializer to try to convert a String into an Int: let possibleNumber = "123" let convertedNumber = Int(possibleNumber) // The type of convertedNumber is "optional Int" Because the initializer in the code above might fail, it returns an optional Int, rather than an Int. To write an optional type, you write a question mark (?) after the name of the type that the optional contains — for example, the type of an optional Int is Int?. An optional Int always contains either some Int value or no value at all. It can’t contain anything else, like a Bool or String value. nil You set an optional variable to a valueless state by assigning it the special value nil: var serverResponseCode: Int? = 404 // serverResponseCode contains an actual Int value of 404 serverResponseCode = nil // serverResponseCode now contains no value If you define an optional variable without providing a default value, the variable is automatically set to nil: var surveyAnswer: String? // surveyAnswer is automatically set to nil You can use an if statement to find out whether an optional contains a value by comparing the optional against nil. You perform this comparison with the “equal to” operator (==) or the “not equal to” operator (!=). If an optional has a value, it’s considered as “not equal to” nil: let possibleNumber = "123" let convertedNumber = Int(possibleNumber)

if convertedNumber != nil { print("convertedNumber contains some integer value.") } // Prints "convertedNumber contains some integer value." You can’t use nil with non-optional constants or variables. If a constant or variable in your code needs to work with the absence of a value under certain conditions, declare it as an optional value of the appropriate type. A constant or variable that’s declared as a non-optional value is guaranteed to never contain a nil value. If you try to assign nil to a non-optional value, you’ll get a compile-time error. This separation of optional and non-optional values lets you explicitly mark what information can be missing, and makes it easier to write code that handle missing values. You can’t accidentally treat an optional as if it were non-optional because this mistake produces an error at compile time. After you unwrap the value, none of the other code that works with that value needs to check for nil, so there’s no need to repeatedly check the same value in different parts of your code. When you access an optional value, your code always handles both the nil and non-nil case. There are several things you can do when a value is missing, as described in the following sections: Skip the code that operates on the value when it’s nil. Propagate the nil value, by returning nil or using the ?. operator described in Optional Chaining. Provide a fallback value, using the ?? operator. Stop program execution, using the ! operator. Note In Objective-C, nil is a pointer to a nonexistent object. In Swift, nil isn’t a pointer — it’s the absence of a value of a certain type. Optionals of any type can be set to nil, not just object types. Optional Binding You use optional binding to find out whether an optional contains a value, and if so, to make that value available as a temporary constant or variable. Optional binding can be used with if, guard, and while statements to check for a value inside an optional, and to extract that value into a constant or variable, as part of a single action. For more information about if, guard, and while statements, see Control Flow. Write an optional binding for an if statement as follows: if let <#constantName#> = <#someOptional#> { <#statements#> } You can rewrite the possibleNumber example from the Optionals section to use optional binding rather than forced unwrapping: if let actualNumber = Int(possibleNumber) { print("The string "(possibleNumber)" has an integer value of (actualNumber)") } else { print("The string "(possibleNumber)" couldn't be converted to an integer") } // Prints "The string "123" has an integer value of 123" This code can be read as: “If the optional Int returned by Int(possibleNumber) contains a value, set a new constant called actualNumber to the value contained in the optional.” If the conversion is successful, the actualNumber constant becomes available for use within the first branch of the if statement. It has already been initialized with the value contained within the optional, and has the corresponding non-optional type. In this case, the type of possibleNumber is Int?, so the type of actualNumber is Int. If you don’t need to refer to the original, optional constant or variable after accessing the value it contains, you can use the same name for the new constant or variable: let myNumber = Int(possibleNumber) // Here, myNumber is an optional integer if let myNumber = myNumber { // Here, myNumber is a non-optional integer print("My number is (myNumber)") } // Prints "My number is 123" This code starts by checking whether myNumber contains a value, just like the code in the previous example. If myNumber has a value, the value of a new constant named myNumber is set to that value. Inside the body of the if statement, writing myNumber refers to that new non-optional constant. Writing myNumber before or after the if statement refers to the original optional integer constant. Because this kind of code is so common, you can use a shorter spelling to unwrap an optional value: Write just the name of the constant or variable that you’re unwrapping. The new, unwrapped constant or variable implicitly uses the same name as the optional value. if let myNumber { print("My number is (myNumber)") } // Prints "My number is 123" You can use both constants and variables with optional binding. If you wanted to manipulate the value of myNumber within the first branch of the if statement, you could write if var myNumber instead, and the value contained within the optional would be made available as a variable rather than a constant. Changes you make to myNumber inside the body of the if statement apply only to that local variable, not to the original, optional constant or variable that you unwrapped. You can include as many optional bindings and Boolean conditions in a single if statement as you need to, separated by commas. If any of the values in the optional bindings are nil or any Boolean condition evaluates to false, the whole if statement’s condition is considered to be false. The following if statements are equivalent: if let firstNumber = Int("4"), let secondNumber = Int("42"), firstNumber < secondNumber && secondNumber < 100 { print("(firstNumber) < (secondNumber) < 100") } // Prints "4 < 42 < 100"

if let firstNumber = Int("4") { if let secondNumber = Int("42") { if firstNumber < secondNumber && secondNumber < 100 { print("(firstNumber) < (secondNumber) < 100") } } } // Prints "4 < 42 < 100" Constants and variables created with optional binding in an if statement are available only within the body of the if statement. In contrast, the constants and variables created with a guard statement are available in the lines of code that follow the guard statement, as described in Early Exit. Providing a Fallback Value Another way to handle a missing value is to supply a default value using the nil-coalescing operator (??). If the optional on the left of the ?? isn’t nil, that value is unwrapped and used. Otherwise, the value on the right of ?? is used. For example, the code below greets someone by name if one is specified, and uses a generic greeting when the name is nil. let name: String? = nil let greeting = "Hello, " + (name ?? "friend") + "!" print(greeting) // Prints "Hello, friend!" For more information about using ?? to provide a fallback value, see Nil-Coalescing Operator. Force Unwrapping When nil represents an unrecoverable failure, such as a programmer error or corrupted state, you can access the underlying value by adding an exclamation mark (!) to the end of the optional’s name. This is known as force unwrapping the optional’s value. When you force unwrap a non-nil value, the result is its unwrapped value. Force unwrapping a nil value triggers a runtime error. The ! is, effectively, a shorter spelling of fatalError(_:file:line:). For example, the code below shows two equivalent approaches: let possibleNumber = "123" let convertedNumber = Int(possibleNumber)

let number = convertedNumber!

guard let number = convertedNumber else { fatalError("The number was invalid") } Both versions of the code above depend on convertedNumber always containing a value. Writing that requirement as part of the code, using either of the approaches above, lets your code check that the requirement is true at runtime. For more information about enforcing data requirements and checking assumptions at runtime, see Assertions and Preconditions. Implicitly Unwrapped Optionals As described above, optionals indicate that a constant or variable is allowed to have “no value”. Optionals can be checked with an if statement to see if a value exists, and can be conditionally unwrapped with optional binding to access the optional’s value if it does exist. Sometimes it’s clear from a program’s structure that an optional will always have a value, after that value is first set. In these cases, it’s useful to remove the need to check and unwrap the optional’s value every time it’s accessed, because it can be safely assumed to have a value all of the time. These kinds of optionals are defined as implicitly unwrapped optionals. You write an implicitly unwrapped optional by placing an exclamation point (String!) rather than a question mark (String?) after the type that you want to make optional. Rather than placing an exclamation point after the optional’s name when you use it, you place an exclamation point after the optional’s type when you declare it. Implicitly unwrapped optionals are useful when an optional’s value is confirmed to exist immediately after the optional is first defined and can definitely be assumed to exist at every point thereafter. The primary use of implicitly unwrapped optionals in Swift is during class initialization, as described in Unowned References and Implicitly Unwrapped Optional Properties. Don’t use an implicitly unwrapped optional when there’s a possibility of a variable becoming nil at a later point. Always use a normal optional type if you need to check for a nil value during the lifetime of a variable. An implicitly unwrapped optional is a normal optional behind the scenes, but can also be used like a non-optional value, without the need to unwrap the optional value each time it’s accessed. The following example shows the difference in behavior between an optional string and an implicitly unwrapped optional string when accessing their wrapped value as an explicit String: let possibleString: String? = "An optional string." let forcedString: String = possibleString! // Requires explicit unwrapping

let assumedString: String! = "An implicitly unwrapped optional string." let implicitString: String = assumedString // Unwrapped automatically You can think of an implicitly unwrapped optional as giving permission for the optional to be force-unwrapped if needed. When you use an implicitly unwrapped optional value, Swift first tries to use it as an ordinary optional value; if it can’t be used as an optional, Swift force-unwraps the value. In the code above, the optional value assumedString is force-unwrapped before assigning its value to implicitString because implicitString has an explicit, non-optional type of String. In code below, optionalString doesn’t have an explicit type so it’s an ordinary optional. let optionalString = assumedString // The type of optionalString is "String?" and assumedString isn't force-unwrapped. If an implicitly unwrapped optional is nil and you try to access its wrapped value, you’ll trigger a runtime error. The result is exactly the same as if you write an exclamation point to force unwrap a normal optional that doesn’t contain a value. You can check whether an implicitly unwrapped optional is nil the same way you check a normal optional: if assumedString != nil { print(assumedString!) } // Prints "An implicitly unwrapped optional string." You can also use an implicitly unwrapped optional with optional binding, to check and unwrap its value in a single statement: if let definiteString = assumedString { print(definiteString) } // Prints "An implicitly unwrapped optional string." Error Handling You use error handling to respond to error conditions your program may encounter during execution. In contrast to optionals, which can use the presence or absence of a value to communicate success or failure of a function, error handling allows you to determine the underlying cause of failure, and, if necessary, propagate the error to another part of your program. When a function encounters an error condition, it throws an error. That function’s caller can then catch the error and respond appropriately. func canThrowAnError() throws { // this function may or may not throw an error } A function indicates that it can throw an error by including the throws keyword in its declaration. When you call a function that can throw an error, you prepend the try keyword to the expression. Swift automatically propagates errors out of their current scope until they’re handled by a catch clause. do { try canThrowAnError() // no error was thrown } catch { // an error was thrown } A do statement creates a new containing scope, which allows errors to be propagated to one or more catch clauses. Here’s an example of how error handling can be used to respond to different error conditions: func makeASandwich() throws { // ... }

do { try makeASandwich() eatASandwich() } catch SandwichError.outOfCleanDishes { washDishes() } catch SandwichError.missingIngredients(let ingredients) { buyGroceries(ingredients) } In this example, the makeASandwich() function will throw an error if no clean dishes are available or if any ingredients are missing. Because makeASandwich() can throw an error, the function call is wrapped in a try expression. By wrapping the function call in a do statement, any errors that are thrown will be propagated to the provided catch clauses. If no error is thrown, the eatASandwich() function is called. If an error is thrown and it matches the SandwichError.outOfCleanDishes case, then the washDishes() function will be called. If an error is thrown and it matches the SandwichError.missingIngredients case, then the buyGroceries(:) function is called with the associated [String] value captured by the catch pattern. Throwing, catching, and propagating errors is covered in greater detail in Error Handling. Assertions and Preconditions Assertions and preconditions are checks that happen at runtime. You use them to make sure an essential condition is satisfied before executing any further code. If the Boolean condition in the assertion or precondition evaluates to true, code execution continues as usual. If the condition evaluates to false, the current state of the program is invalid; code execution ends, and your app is terminated. You use assertions and preconditions to express the assumptions you make and the expectations you have while coding, so you can include them as part of your code. Assertions help you find mistakes and incorrect assumptions during development, and preconditions help you detect issues in production. In addition to verifying your expectations at runtime, assertions and preconditions also become a useful form of documentation within the code. Unlike the error conditions discussed in Error Handling above, assertions and preconditions aren’t used for recoverable or expected errors. Because a failed assertion or precondition indicates an invalid program state, there’s no way to catch a failed assertion. Recovering from an invalid state is impossible. When an assertion fails, at least one piece of the program’s data is invalid — but you don’t know why it’s invalid or whether an additional state is also invalid. Using assertions and preconditions isn’t a substitute for designing your code in such a way that invalid conditions are unlikely to arise. However, using them to enforce valid data and state causes your app to terminate more predictably if an invalid state occurs, and helps make the problem easier to debug. When assumptions aren’t checked, you might not notice this kind problem until much later when code elsewhere starts failing visibly, and after user data has been silently corrupted. Stopping execution as soon as an invalid state is detected also helps limit the damage caused by that invalid state. The difference between assertions and preconditions is in when they’re checked: Assertions are checked only in debug builds, but preconditions are checked in both debug and production builds. In production builds, the condition inside an assertion isn’t evaluated. This means you can use as many assertions as you want during your development process, without impacting performance in production. Debugging with Assertions You write an assertion by calling the assert(::file:line:) function from the Swift standard library. You pass this function an expression that evaluates to true or false and a message to display if the result of the condition is false. For example: let age = -3 assert(age >= 0, "A person's age can't be less than zero.") // This assertion fails because -3 isn't >= 0. In this example, code execution continues if age >= 0 evaluates to true, that is, if the value of age is nonnegative. If the value of age is negative, as in the code above, then age >= 0 evaluates to false, and the assertion fails, terminating the application. You can omit the assertion message — for example, when it would just repeat the condition as prose. assert(age >= 0) If the code already checks the condition, you use the assertionFailure(:file:line:) function to indicate that an assertion has failed. For example: if age > 10 { print("You can ride the roller-coaster or the ferris wheel.") } else if age >= 0 { print("You can ride the ferris wheel.") } else { assertionFailure("A person's age can't be less than zero.") } Enforcing Preconditions Use a precondition whenever a condition has the potential to be false, but must definitely be true for your code to continue execution. For example, use a precondition to check that a subscript isn’t out of bounds, or to check that a function has been passed a valid value. You write a precondition by calling the precondition(::file:line:) function. You pass this function an expression that evaluates to true or false and a message to display if the result of the condition is false. For example: // In the implementation of a subscript... precondition(index > 0, "Index must be greater than zero.") You can also call the preconditionFailure(:file:line:) function to indicate that a failure has occurred — for example, if the default case of a switch was taken, but all valid input data should have been handled by one of the switch’s other cases. Note If you compile in unchecked mode (-Ounchecked), preconditions aren’t checked. The compiler assumes that preconditions are always true, and it optimizes your code accordingly. However, the fatalError(:file:line:) function always halts execution, regardless of optimization settings. You can use the fatalError(_:file:line:) function during prototyping and early development to create stubs for functionality that hasn’t been implemented yet, by writing fatalError("Unimplemented") as the stub implementation. Because fatal errors are never optimized out, unlike assertions or preconditions, you can be sure that execution always halts if it encounters a stub implementation. Beta Software This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software. Learn more about using Apple’s beta software.

URL: https://docs.swift.org/swift-book/documentation/the-swift-programming-language/attributes The Swift Programming Language (6.0 beta) Attributes Attributes Add information to declarations and types. There are two kinds of attributes in Swift — those that apply to declarations and those that apply to types. An attribute provides additional information about the declaration or type. For example, the discardableResult attribute on a function declaration indicates that, although the function returns a value, the compiler shouldn’t generate a warning if the return value is unused. You specify an attribute by writing the @ symbol followed by the attribute’s name and any arguments that the attribute accepts: @<#attribute name#> @<#attribute name#>(<#attribute arguments#>) Some declaration attributes accept arguments that specify more information about the attribute and how it applies to a particular declaration. These attribute arguments are enclosed in parentheses, and their format is defined by the attribute they belong to. Attached macros and property wrappers also use attribute syntax. For information about how macros expand, see Macro-Expansion Expression. For information about property wrappers, see propertyWrapper. Declaration Attributes You can apply a declaration attribute to declarations only. attached Apply the attached attribute to a macro declaration. The arguments to this attribute indicate the macro’s role. For a macro that has multiple roles, apply the attached macro multiple times, once for each role. The first argument to this attribute indicates the macros role: Peer macros Write peer as the first argument to this attribute. The type that implements the macro conforms to the PeerMacro protocol. These macros produce new declarations in the same scope as the declaration that the macro is attached to. For example, applying a peer macro to a method of a structure can define additional methods and properties on that structure. Member macros Write member as the first argument to this attribute. The type that implements the macro conforms to the MemberMacro protocol. These macros produce new declarations that are members of the type or extension that the macro is attached to. For example, applying a member macro to a structure declaration can define additional methods and properties on that structure. Member attribute Write memberAttribute as the first argument to this attribute. The type that implements the macro conforms to the MemberAttributeMacro protocol. These macros add attributes to members of the type or extension that the macro is attached to. Accessor macros Write accessor as the first argument to this attribute. The type that implements the macro conforms to the AccessorMacro protocol. These macros add accessors to the stored property they’re attached to, turning it into a computed property. Extension macros Write extension as the first argument to this attribute. The type that implements the macro conforms to the ExtensionMacro protocol. These macros can add protocol conformance, a where clause, and new declarations that are members of the type the macro is attached to. If the macro adds protocol conformances, include the conformances: argument and specify those protocols. The conformance list contains protocol names, type aliases that refer to conformance list items, or protocol compositions of conformance list items. An extension macro on a nested type expands to an extension at the top level of that file. You can’t write an extension macro on an extension, a type alias, or a type that’s nested inside a function, or use an extension macro to add an extension that has a peer macro. The peer, member, and accessor macro roles require a names: argument, listing the names of the symbols that the macro generates. The extension macro role also requires a names: argument if the macro adds declarations inside the extension. When a macro declaration includes the names: argument, the macro implementation must generate only symbol with names that match that list. That said, a macro need not generate a symbol for every listed name. The value for that argument is a list of one or more of the following: named(<#name#>) where name is that fixed symbol name, for a name that’s known in advance. overloaded for a name that’s the same as an existing symbol. prefixed(<#prefix#>) where prefix is prepended to the symbol name, for a name that starts with a fixed string. suffixed(<#suffix#>) where suffix is appended to the symbol name, for a name that ends with a fixed string. arbitrary for a name that can’t be determined until macro expansion. As a special case, you can write prefixed($) for a macro that behaves similar to a property wrapper. available Apply this attribute to indicate a declaration’s life cycle relative to certain Swift language versions or certain platforms and operating system versions. The available attribute always appears with a list of two or more comma-separated attribute arguments. These arguments begin with one of the following platform or language names: iOS iOSApplicationExtension macOS macOSApplicationExtension macCatalyst macCatalystApplicationExtension watchOS watchOSApplicationExtension tvOS tvOSApplicationExtension visionOS visionOSApplicationExtension swift You can also use an asterisk (*) to indicate the availability of the declaration on all of the platform names listed above. An available attribute that specifies availability using a Swift version number can’t use the asterisk. The remaining arguments can appear in any order and specify additional information about the declaration’s life cycle, including important milestones. The unavailable argument indicates that the declaration isn’t available on the specified platform. This argument can’t be used when specifying Swift version availability. The introduced argument indicates the first version of the specified platform or language in which the declaration was introduced. It has the following form: introduced: <#version number#> The version number consists of one to three positive integers, separated by periods. The deprecated argument indicates the first version of the specified platform or language in which the declaration was deprecated. It has the following form: deprecated: <#version number#> The optional version number consists of one to three positive integers, separated by periods. Omitting the version number indicates that the declaration is currently deprecated, without giving any information about when the deprecation occurred. If you omit the version number, omit the colon (:) as well. The obsoleted argument indicates the first version of the specified platform or language in which the declaration was obsoleted. When a declaration is obsoleted, it’s removed from the specified platform or language and can no longer be used. It has the following form: obsoleted: <#version number#> The version number consists of one to three positive integers, separated by periods. The message argument provides a textual message that the compiler displays when emitting a warning or error about the use of a deprecated or obsoleted declaration. It has the following form: message: <#message#> The message consists of a string literal. The renamed argument provides a textual message that indicates the new name for a declaration that’s been renamed. The compiler displays the new name when emitting an error about the use of a renamed declaration. It has the following form: renamed: <#new name#> The new name consists of a string literal. You can apply the available attribute with the renamed and unavailable arguments to a type alias declaration, as shown below, to indicate that the name of a declaration changed between releases of a framework or library. This combination results in a compile-time error that the declaration has been renamed. // First release protocol MyProtocol { // protocol definition } // Subsequent release renames MyProtocol protocol MyRenamedProtocol { // protocol definition }

@available(*, unavailable, renamed: "MyRenamedProtocol") typealias MyProtocol = MyRenamedProtocol You can apply multiple available attributes on a single declaration to specify the declaration’s availability on different platforms and different versions of Swift. The declaration that the available attribute applies to is ignored if the attribute specifies a platform or language version that doesn’t match the current target. If you use multiple available attributes, the effective availability is the combination of the platform and Swift availabilities. If an available attribute only specifies an introduced argument in addition to a platform or language name argument, you can use the following shorthand syntax instead: @available(<#platform name#> <#version number#>, *) @available(swift <#version number#>) The shorthand syntax for available attributes concisely expresses availability for multiple platforms. Although the two forms are functionally equivalent, the shorthand form is preferred whenever possible. @available(iOS 10.0, macOS 10.12, *) class MyClass { // class definition } An available attribute that specifies availability using a Swift version number can’t additionally specify a declaration’s platform availability. Instead, use separate available attributes to specify a Swift version availability and one or more platform availabilities. @available(swift 3.0.2) @available(macOS 10.12, ) struct MyStruct { // struct definition } backDeployed Apply this attribute to a function, method, subscript, or computed property to include a copy of the symbol’s implementation in programs that call or access the symbol. You use this attribute to annotate symbols that ship as part of a platform, like the APIs that are included with an operating system. This attribute marks symbols that can be made available retroactively by including a copy of their implementation in programs that access them. Copying the implementation is also known as emitting into the client. This attribute takes a before: argument, specifying the first version of platforms that provide this symbol. These platform versions have the same meaning as the platform version you specify for the available attribute. Unlike the available attribute, the list can’t contain an asterisk () to refer to all versions. For example, consider the following code: @available(iOS 16, ) @backDeployed(before: iOS 17) func someFunction() { / ... */ } In the example above, the iOS SDK provides someFunction() starting in iOS 17. In addition, the SDK makes someFunction() available on iOS 16 using back deployment. When compiling code that calls this function, Swift inserts a layer of indirection that finds the function’s implementation. If the code is run using a version of the SDK that includes this function, the SDK’s implementation is used. Otherwise, the copy included in the caller is used. In the example above, calling someFunction() uses the implementation from the SDK when running on iOS 17 or later, and when running on iOS 16 it uses the copy of someFunction() that’s included in the caller. Note When the caller’s minimum deployment target is the same as or greater than the first version of the SDK that includes the symbol, the compiler can optimize away the runtime check and call the SDK’s implementation directly. In this case, if you access the back-deployed symbol directly, the compiler can also omit the copy of the symbol’s implementation from the client. Functions, methods, subscripts, and computed properties that meet the following criteria can be back deployed: The declaration is public or @usableFromInline. For class instance methods and class type methods, the method is marked final and isn’t marked @objc. The implementation satisfies the requirements for an inlinable function, described in inlinable. discardableResult Apply this attribute to a function or method declaration to suppress the compiler warning when the function or method that returns a value is called without using its result. dynamicCallable Apply this attribute to a class, structure, enumeration, or protocol to treat instances of the type as callable functions. The type must implement either a dynamicallyCall(withArguments:) method, a dynamicallyCall(withKeywordArguments:) method, or both. You can call an instance of a dynamically callable type as if it’s a function that takes any number of arguments. @dynamicCallable struct TelephoneExchange { func dynamicallyCall(withArguments phoneNumber: [Int]) { if phoneNumber == [4, 1, 1] { print("Get Swift help on forums.swift.org") } else { print("Unrecognized number") } } }

let dial = TelephoneExchange()

// Use a dynamic method call. dial(4, 1, 1) // Prints "Get Swift help on forums.swift.org"

dial(8, 6, 7, 5, 3, 0, 9) // Prints "Unrecognized number"

// Call the underlying method directly. dial.dynamicallyCall(withArguments: [4, 1, 1]) The declaration of the dynamicallyCall(withArguments:) method must have a single parameter that conforms to the ExpressibleByArrayLiteral protocol — like [Int] in the example above. The return type can be any type. You can include labels in a dynamic method call if you implement the dynamicallyCall(withKeywordArguments:) method. @dynamicCallable struct Repeater { func dynamicallyCall(withKeywordArguments pairs: KeyValuePairs<String, Int>) -> String { return pairs .map { label, count in repeatElement(label, count: count).joined(separator: " ") } .joined(separator: "\n") } }

let repeatLabels = Repeater() print(repeatLabels(a: 1, b: 2, c: 3, b: 2, a: 1)) // a // b b // c c c // b b // a The declaration of the dynamicallyCall(withKeywordArguments:) method must have a single parameter that conforms to the ExpressibleByDictionaryLiteral protocol, and the return type can be any type. The parameter’s Key must be ExpressibleByStringLiteral. The previous example uses KeyValuePairs as the parameter type so that callers can include duplicate parameter labels — a and b appear multiple times in the call to repeat. If you implement both dynamicallyCall methods, dynamicallyCall(withKeywordArguments:) is called when the method call includes keyword arguments. In all other cases, dynamicallyCall(withArguments:) is called. You can only call a dynamically callable instance with arguments and a return value that match the types you specify in one of your dynamicallyCall method implementations. The call in the following example doesn’t compile because there isn’t an implementation of dynamicallyCall(withArguments:) that takes KeyValuePairs<String, String>. repeatLabels(a: "four") // Error dynamicMemberLookup Apply this attribute to a class, structure, enumeration, or protocol to enable members to be looked up by name at runtime. The type must implement a subscript(dynamicMember:) subscript. In an explicit member expression, if there isn’t a corresponding declaration for the named member, the expression is understood as a call to the type’s subscript(dynamicMember:) subscript, passing information about the member as the argument. The subscript can accept a parameter that’s either a key path or a member name; if you implement both subscripts, the subscript that takes key path argument is used. An implementation of subscript(dynamicMember:) can accept key paths using an argument of type KeyPath, WritableKeyPath, or ReferenceWritableKeyPath. It can accept member names using an argument of a type that conforms to the ExpressibleByStringLiteral protocol — in most cases, String. The subscript’s return type can be any type. Dynamic member lookup by member name can be used to create a wrapper type around data that can’t be type checked at compile time, such as when bridging data from other languages into Swift. For example: @dynamicMemberLookup struct DynamicStruct { let dictionary = ["someDynamicMember": 325, "someOtherMember": 787] subscript(dynamicMember member: String) -> Int { return dictionary[member] ?? 1054 } } let s = DynamicStruct()

// Use dynamic member lookup. let dynamic = s.someDynamicMember print(dynamic) // Prints "325"

// Call the underlying subscript directly. let equivalent = s[dynamicMember: "someDynamicMember"] print(dynamic == equivalent) // Prints "true" Dynamic member lookup by key path can be used to implement a wrapper type in a way that supports compile-time type checking. For example: struct Point { var x, y: Int }

@dynamicMemberLookup struct PassthroughWrapper { var value: Value subscript(dynamicMember member: KeyPath<Value, T>) -> T { get { return value[keyPath: member] } } }

let point = Point(x: 381, y: 431) let wrapper = PassthroughWrapper(value: point) print(wrapper.x) freestanding Apply the freestanding attribute to the declaration of a freestanding macro. frozen Apply this attribute to a structure or enumeration declaration to restrict the kinds of changes you can make to the type. This attribute is allowed only when compiling in library evolution mode. Future versions of the library can’t change the declaration by adding, removing, or reordering an enumeration’s cases or a structure’s stored instance properties. These changes are allowed on nonfrozen types, but they break ABI compatibility for frozen types. Note When the compiler isn’t in library evolution mode, all structures and enumerations are implicitly frozen, and this attribute is ignored. In library evolution mode, code that interacts with members of nonfrozen structures and enumerations is compiled in a way that allows it to continue working without recompiling even if a future version of the library adds, removes, or reorders some of that type’s members. The compiler makes this possible using techniques like looking up information at runtime and adding a layer of indirection. Marking a structure or enumeration as frozen gives up this flexibility to gain performance: Future versions of the library can make only limited changes to the type, but the compiler can make additional optimizations in code that interacts with the type’s members. Frozen types, the types of the stored properties of frozen structures, and the associated values of frozen enumeration cases must be public or marked with the usableFromInline attribute. The properties of a frozen structure can’t have property observers, and expressions that provide the initial value for stored instance properties must follow the same restrictions as inlinable functions, as discussed in inlinable. To enable library evolution mode on the command line, pass the -enable-library-evolution option to the Swift compiler. To enable it in Xcode, set the “Build Libraries for Distribution” build setting (BUILD_LIBRARY_FOR_DISTRIBUTION) to Yes, as described in Xcode Help. A switch statement over a frozen enumeration doesn’t require a default case, as discussed in Switching Over Future Enumeration Cases. Including a default or @unknown default case when switching over a frozen enumeration produces a warning because that code is never executed. GKInspectable Apply this attribute to expose a custom GameplayKit component property to the SpriteKit editor UI. Applying this attribute also implies the objc attribute. inlinable Apply this attribute to a function, method, computed property, subscript, convenience initializer, or deinitializer declaration to expose that declaration’s implementation as part of the module’s public interface. The compiler is allowed to replace calls to an inlinable symbol with a copy of the symbol’s implementation at the call site. Inlinable code can interact with open and public symbols declared in any module, and it can interact with internal symbols declared in the same module that are marked with the usableFromInline attribute. Inlinable code can’t interact with private or fileprivate symbols. This attribute can’t be applied to declarations that are nested inside functions or to fileprivate or private declarations. Functions and closures that are defined inside an inlinable function are implicitly inlinable, even though they can’t be marked with this attribute. main Apply this attribute to a structure, class, or enumeration declaration to indicate that it contains the top-level entry point for program flow. The type must provide a main type function that doesn’t take any arguments and returns Void. For example: @main struct MyTopLevel { static func main() { // Top-level code goes here } } Another way to describe the requirements of the main attribute is that the type you write this attribute on must satisfy the same requirements as types that conform to the following hypothetical protocol: protocol ProvidesMain { static func main() throws } The Swift code you compile to make an executable can contain at most one top-level entry point, as discussed in Top-Level Code. nonobjc Apply this attribute to a method, property, subscript, or initializer declaration to suppress an implicit objc attribute. The nonobjc attribute tells the compiler to make the declaration unavailable in Objective-C code, even though it’s possible to represent it in Objective-C. Applying this attribute to an extension has the same effect as applying it to every member of that extension that isn’t explicitly marked with the objc attribute. You use the nonobjc attribute to resolve circularity for bridging methods in a class marked with the objc attribute, and to allow overloading of methods and initializers in a class marked with the objc attribute. A method marked with the nonobjc attribute can’t override a method marked with the objc attribute. However, a method marked with the objc attribute can override a method marked with the nonobjc attribute. Similarly, a method marked with the nonobjc attribute can’t satisfy a protocol requirement for a method marked with the objc attribute. NSApplicationMain Deprecated This attribute is deprecated; use the main attribute instead. In Swift 6, using this attribute will be an error. Apply this attribute to a class to indicate that it’s the app delegate. Using this attribute is equivalent to calling the NSApplicationMain(::) function. If you don’t use this attribute, supply a main.swift file with code at the top level that calls the NSApplicationMain(::) function as follows: import AppKit NSApplicationMain(CommandLine.argc, CommandLine.unsafeArgv) The Swift code you compile to make an executable can contain at most one top-level entry point, as discussed in Top-Level Code. NSCopying Apply this attribute to a stored variable property of a class. This attribute causes the property’s setter to be synthesized with a copy of the property’s value — returned by the copyWithZone(:) method — instead of the value of the property itself. The type of the property must conform to the NSCopying protocol. The NSCopying attribute behaves in a way similar to the Objective-C copy property attribute. NSManaged Apply this attribute to an instance method or stored variable property of a class that inherits from NSManagedObject to indicate that Core Data dynamically provides its implementation at runtime, based on the associated entity description. For a property marked with the NSManaged attribute, Core Data also provides the storage at runtime. Applying this attribute also implies the objc attribute. objc Apply this attribute to any declaration that can be represented in Objective-C — for example, nonnested classes, protocols, nongeneric enumerations (constrained to integer raw-value types), properties and methods (including getters and setters) of classes, protocols and optional members of a protocol, initializers, and subscripts. The objc attribute tells the compiler that a declaration is available to use in Objective-C code. Applying this attribute to an extension has the same effect as applying it to every member of that extension that isn’t explicitly marked with the nonobjc attribute. The compiler implicitly adds the objc attribute to subclasses of any class defined in Objective-C. However, the subclass must not be generic, and must not inherit from any generic classes. You can explicitly add the objc attribute to a subclass that meets these criteria, to specify its Objective-C name as discussed below. Protocols that are marked with the objc attribute can’t inherit from protocols that aren’t marked with this attribute. The objc attribute is also implicitly added in the following cases: The declaration is an override in a subclass, and the superclass’s declaration has the objc attribute. The declaration satisfies a requirement from a protocol that has the objc attribute. The declaration has the IBAction, IBSegueAction, IBOutlet, IBDesignable, IBInspectable, NSManaged, or GKInspectable attribute. If you apply the objc attribute to an enumeration, each enumeration case is exposed to Objective-C code as the concatenation of the enumeration name and the case name. The first letter of the case name is capitalized. For example, a case named venus in a Swift Planet enumeration is exposed to Objective-C code as a case named PlanetVenus. The objc attribute optionally accepts a single attribute argument, which consists of an identifier. The identifier specifies the name to be exposed to Objective-C for the entity that the objc attribute applies to. You can use this argument to name classes, enumerations, enumeration cases, protocols, methods, getters, setters, and initializers. If you specify the Objective-C name for a class, protocol, or enumeration, include a three-letter prefix on the name, as described in Conventions in Programming with Objective-C. The example below exposes the getter for the enabled property of the ExampleClass to Objective-C code as isEnabled rather than just as the name of the property itself. class ExampleClass: NSObject { @objc var enabled: Bool { @objc(isEnabled) get { // Return the appropriate value } } } For more information, see Importing Swift into Objective-C. Note The argument to the objc attribute can also change the runtime name for that declaration. You use the runtime name when calling functions that interact with the Objective-C runtime, like NSClassFromString(:), and when specifying class names in an app’s Info.plist file. If you specify a name by passing an argument, that name is used as the name in Objective-C code and as the runtime name. If you omit the argument, the name used in Objective-C code matches the name in Swift code, and the runtime name follows the normal Swift compiler convention of name mangling. objcMembers Apply this attribute to a class declaration, to implicitly apply the objc attribute to all Objective-C compatible members of the class, its extensions, its subclasses, and all of the extensions of its subclasses. Most code should use the objc attribute instead, to expose only the declarations that are needed. If you need to expose many declarations, you can group them in an extension that has the objc attribute. The objcMembers attribute is a convenience for libraries that make heavy use of the introspection facilities of the Objective-C runtime. Applying the objc attribute when it isn’t needed can increase your binary size and adversely affect performance. preconcurrency Apply this attribute to a declaration, to suppress strict concurrency checking. You can apply this attribute to the following kinds of declarations: Imports Structures, classes, and actors Enumerations and enumeration cases Protocols Variables and constants Subscripts Initializers Functions On an import declaration, this attribute reduces the strictness of concurrency checking for code that uses types from the imported module. Specifically, types from the imported module that aren’t explicitly marked as nonsendable can be used in a context that requires sendable types. On other declarations, this attribute reduces the strictness of concurrency checking for code that uses the symbol being declared. When you use this symbol in a scope that has minimal concurrency checking, concurrency-related constraints specified by that symbol, such as Sendable requirements or global actors, aren’t checked. You can use this attribute as follows, to aid in migrating code to strict concurrency checking: Enable strict checking. Annotate imports with the preconcurrency attribute for modules that haven’t enabled strict checking. After migrating a module to strict checking, remove the preconcurrency attribute. The compiler warns you about any places where the preconcurrency attribute on an import no longer has an effect and should be removed. For other declarations, add the preconcurrency attribute when you add concurrency-related constraints to the declaration, if you still have clients that haven’t migrated to strict checking. Remove the preconcurrency attribute after all your clients have migrated. Declarations from Objective-C are always imported as if they were marked with the preconcurrency attribute. propertyWrapper Apply this attribute to a class, structure, or enumeration declaration to use that type as a property wrapper. When you apply this attribute to a type, you create a custom attribute with the same name as the type. Apply that new attribute to a property of a class, structure, or enumeration to wrap access to the property through an instance of the wrapper type; apply the attribute to a local stored variable declaration to wrap access to the variable the same way. Computed variables, global variables, and constants can’t use property wrappers. The wrapper must define a wrappedValue instance property. The wrapped value of the property is the value that the getter and setter for this property expose. In most cases, wrappedValue is a computed value, but it can be a stored value instead. The wrapper defines and manages any underlying storage needed by its wrapped value. The compiler synthesizes storage for the instance of the wrapper type by prefixing the name of the wrapped property with an underscore (_) — for example, the wrapper for someProperty is stored as _someProperty. The synthesized storage for the wrapper has an access control level of private. A property that has a property wrapper can include willSet and didSet blocks, but it can’t override the compiler-synthesized get or set blocks. Swift provides two forms of syntactic sugar for initialization of a property wrapper. You can use The file is too long and its contents have been truncated.

Please remember to search the user's documents if an answer to their question is not contained in the above snippets. msearch(["preload assets"])# 【0†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】 /// Removes 3D content when then game is over. func clear() { spaceOrigin.children.removeAll() }

/// Resets game state information.
func reset() {
    isPlaying = false
    isPaused = false
    isSharePlaying = false
    isFinished = false
    isSoloReady = false
    timeLeft = GameModel.gameTime
    isCountDownReady = false
    countDown = 3
    score = 0
    isInputSelected = false
    inputKind = .hands
    players = initialPlayers
    
    #if targetEnvironment(simulator)
    Player.localName = players.first!.name
    #endif
    
    clouds = (0..<30).map { Cloud(id: $0, isHappy: false) }
    cloudNumber = 0
    hitCounts = [:]
    cloudIsHit = [:]
    cloudEntities = []
    isUsingControllerInput = false
    controllerX = 0
    controllerY = 90.0
    
    victoryPlayer.pause()
    gameplayPlayer.pause()
    
    clear()
}

/// Preload assets when the app launches to avoid pop-in during the game.
init() {
    Task { @MainActor in
        
        guard let beamAsset = await loadFromRealityComposerPro(
            named: BundleAssets.heartBlasterEntity,
            fromSceneNamed: BundleAssets.heartBlasterScene
        ) else {
            fatalError("Unable to load beam from Reality Composer Pro project.")
        }
        beam = beamAsset
        beam.name = BundleAssets.beamName
        
        // Position the beam relative to the user's hand.
        beam.position = .init(x: 0, y: 0, z: -0.3)
        beam.orientation = simd_quatf(
            Rotation3D(angle: .degrees(90), axis: .y)
                .rotated(by: Rotation3D(angle: .degrees(-90), axis: .z))
        )
        
        floorBeam = beam.clone(recursive: true)
        floorBeam.name = "floorBeam"
        floorBeam.position.z += 0.3
        
        let fireworks = try await Entity(named: "fireworks")
        globalFireworks = fireworks.children.first!.children.first!
        
        turret = await loadFromRealityComposerPro(named: BundleAssets.heartTurretEntity, fromSceneNamed: BundleAssets.heartTurretScene)
        turret?.name = "Holder"
        turret?.position = .init(x: 0, y: 0.25, z: -1.7)
        turret?.scale *= 0.3
        
        heart = await loadFromRealityComposerPro(named: BundleAssets.heartLightEntity, fromSceneNamed: BundleAssets.heartLightScene)
        heart?.name = "Heart Projector"
        heart?.generateCollisionShapes(recursive: true)
        heart?.position = .init(x: 0, y: 0.25, z: -1.7)
        heart?.position.y += 0.68
        heart?.scale *= 0.22
        heart?.components[InputTargetComponent.self] = InputTargetComponent(allowedInputTypes: .all)
        
        cloudTemplate = try? await Entity(named: BundleAssets.cloud)
        
        guard turret != nil, heart != nil, cloudTemplate != nil else {
            fatalError("Error loading assets.")
        }
        
        do {
            for number in 1...4 {
                let resource = try await AudioFileResource(named: "cloudHit\(number).m4a")
                cloudSounds.append(resource)
            }
        } catch {
            fatalError("Error loading cloud sound resources.")
        }
        
        // Generate animations inside the cloud models.

【1†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

? 0

        return Circle()
            .fill(Color(white: 0.85,
                        opacity: 0.85))
            .frame(width: 30, height: 30)
            .overlay {
                ZStack {
                    Circle()
                        .trim(from: 0, to: CGFloat(fractionCompleted))
                        .stroke(strokeColor, style: StrokeStyle(lineWidth: CGFloat(strokeWidth), lineCap: .round))
                        .rotationEffect(.degrees(-90))
                        .frame(width: 20, height: 20)
                        .animation(.linear, value: fractionCompleted)
                }
            }
    }
}

}

struct Thumbnail_Previews: PreviewProvider { @State static var sessionManager = SessionManager()

static var previews: some View {
    if let session = sessionManager.sessions.first {
        Thumbnail(localSession: session)
    } else {
        ProgressView()
    }
}

}

url: https://developer.apple.com/documentation/backgroundassets/downloading_essential_assets_in_the_background title: Downloading essential assets in the background description: Fetch the assets your app requires before its first launch using an app extension and the Background Assets framework. code_title: VideoSelector.swift code_sample: import SwiftUI

struct VideoSelector: View { @ObservedObject var session: LocalSession var onDelete: () -> Void

var body: some View {
    let selectable = session.state != .remote

    let view = NavigationLink(value: selectable ? session : nil) {
        HStack {
            HStack {
                Thumbnail(localSession: session)
                SessionDescription(session: session, style: .short)
            }
            
            if session.essential {
                Spacer()
                Circle()
                    .fill(.green)
                    .frame(width: 10, alignment: (.trailing))
            }
        }
    }
    .deleteDisabled(session.state != .downloaded)
    #if os(macOS)
    .swipeActions(edge: .trailing) {
        if session.state == .downloaded {
            Button(role: .destructive, action: self.onDelete) {
                Label("Delete", systemImage: "trash")
            }
        }
    }
    #endif

    if selectable {
        view
    } else {
        view.foregroundColor(.gray)
            .disabled(true)
    }
}

}

struct VideoSelector_Previews: PreviewProvider { @State static private var sessionManager = SessionManager()

static var previews: some View {
    NavigationSplitView {
        if let session = sessionManager.sessions.first {
            VideoSelector(session: session) {}
        } else {
            ProgressView()
        }
    } detail: {
        Text("Detail!")
    }
}

}

url: https://developer.apple.com/documentation/backgroundassets/downloading_essential_assets_in_the_background title: Downloading essential assets in the background description: Fetch the assets your app requires before its first launch using an app extension and the Background Assets framework.

【2†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

await withCheckedThrowingContinuation({ continuation in imageGenerator.generateCGImageAsynchronously(for: time) { image, time, error in if let image = image { continuation.resume(returning: image) } else if let error = error { continuation.resume(throwing: error) } else { continuation.resume(throwing: ImageGenerationError.noResult) } } }) }

public static func fileURL(for session: Session) -> URL {
    return SharedSettings.sessionStorageURL
        .appending(component: "Session_\(session.sessionId)")
        .appendingPathExtension("mp4")
}

// MARK: Decodable

private enum CodingKeys: String, CodingKey {
    case fileURL
}

required init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    self.fileURL = try container.decode(Foundation.URL.self, forKey: .fileURL)
    try super.init(from: decoder)
}

}

url: https://developer.apple.com/documentation/backgroundassets/downloading_essential_assets_in_the_background title: Downloading essential assets in the background description: Fetch the assets your app requires before its first launch using an app extension and the Background Assets framework. code_title: Session.swift code_sample: import Foundation

struct WWDC { enum Year: UInt, Equatable, CaseIterable, CustomStringConvertible, Codable { var description: String { guard let numeric = self.numericRepresentation else { return "WWDC" }

        return "WWDC\(numeric)"
    }
    
    fileprivate var numericRepresentation: UInt? {
        guard self != .unknown else {
            return nil
        }
        
        return self.rawValue
    }
    
    case unknown
    case fifteen = 15
    case nineteen = 19
    case twenty = 20
    case twentyOne = 21
    case twentyTwo = 22
    case twentyThree = 23
}

}

class Session: Codable { let sessionId: Int let title: String let description: String let fileSize: UInt let authors: [String] let year: WWDC.Year let thumbnailOffsetInSeconds: Float let essential: Bool let URL: URL

init(sessionId: Int,
     title: String,
     description: String,
     fileSize: UInt,
     authors: [String],
     year: WWDC.Year,
     thumbnailOffsetInSeconds: Float,
     essential: Bool,
     URL: URL) {
    
    self.sessionId = sessionId
    self.title = title
    self.description = description
    self.fileSize = fileSize
    self.authors = authors
    self.year = year
    self.thumbnailOffsetInSeconds = thumbnailOffsetInSeconds
    self.essential = essential
    self.URL = URL
}

}

extension Session: Hashable { static func == (lhs: Session, rhs: Session) -> Bool { return lhs.sessionId == rhs.sessionId }

func hash(into hasher: inout Hasher) {
    hasher.combine(self.sessionId)
}

}

url: https://developer.apple.com/documentation/backgroundassets/downloading_essential_assets_in_the_background title: Downloading essential assets in the background description: Fetch the assets your app requires before its first launch using an app extension and the Background Assets framework.

【3†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

{ guard self != .unknown else { return nil }

        return self.rawValue
    }
    
    case unknown
    case fifteen = 15
    case nineteen = 19
    case twenty = 20
    case twentyOne = 21
    case twentyTwo = 22
    case twentyThree = 23
}

}

class Session: Codable { let sessionId: Int let title: String let description: String let fileSize: UInt let authors: [String] let year: WWDC.Year let thumbnailOffsetInSeconds: Float let essential: Bool let URL: URL

init(sessionId: Int,
     title: String,
     description: String,
     fileSize: UInt,
     authors: [String],
     year: WWDC.Year,
     thumbnailOffsetInSeconds: Float,
     essential: Bool,
     URL: URL) {
    
    self.sessionId = sessionId
    self.title = title
    self.description = description
    self.fileSize = fileSize
    self.authors = authors
    self.year = year
    self.thumbnailOffsetInSeconds = thumbnailOffsetInSeconds
    self.essential = essential
    self.URL = URL
}

}

extension Session: Hashable { static func == (lhs: Session, rhs: Session) -> Bool { return lhs.sessionId == rhs.sessionId }

func hash(into hasher: inout Hasher) {
    hasher.combine(self.sessionId)
}

}

url: https://developer.apple.com/documentation/backgroundassets/downloading_essential_assets_in_the_background title: Downloading essential assets in the background description: Fetch the assets your app requires before its first launch using an app extension and the Background Assets framework. code_title: App.swift code_sample: import SwiftUI import OSLog

public extension Logger { static let app = Logger(subsystem: "com.example.apple-samplecode.WWDC-Sessions", category: "app") }

@main struct WWDCSessionsApp: App { @StateObject private var sessionManager = SessionManager()

var body: some Scene {
    WindowGroup {
        ContentView()
            .environmentObject(self.sessionManager)
    }
    #if os(macOS)
    .defaultSize(width: 900, height: 750)
    #endif
}

}

url: https://developer.apple.com/documentation/backgroundassets/downloading_essential_assets_in_the_background title: Downloading essential assets in the background description: Fetch the assets your app requires before its first launch using an app extension and the Background Assets framework. code_title: ContentView.swift code_sample: import SwiftUI

struct ContentView: View { @State var selections: Set = Set() @State var selection: LocalSession? = nil @State var visibility: NavigationSplitViewVisibility = .doubleColumn

var body: some View {
    NavigationSplitView(columnVisibility: $visibility) {
        VideoSelectorSidebar(selections: $selections)
    } detail: {
        DetailView(selection: $selection)
    }
    .navigationSplitViewStyle(.balanced)
    .onChange(of: selections, perform: { newSelections in
        if newSelections.count == 1 {
            self.selection = newSelections.first!
        } else if newSelections.isEmpty {
            self.selection = nil
        }
    })
}

}

struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() .environmentObject(SessionManager()) } }

url: https://developer.apple.com/documentation/backgroundassets/downloading_essential_assets_in_the_background title: Downloading essential assets in the background description: Fetch the assets your app requires before its first launch using an app extension and the Background Assets framework.

【4†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

{ return (.performDefaultHandling, nil) } }

url: https://developer.apple.com/documentation/backgroundassets/downloading_essential_assets_in_the_background title: Downloading essential assets in the background description: Fetch the assets your app requires before its first launch using an app extension and the Background Assets framework. code_title: DetailView.swift code_sample: import Foundation import SwiftUI import AVKit

struct DetailView: View { @Binding var selection: LocalSession? @State private var avPlayer = AVPlayer()

func playCurrentSelection() {
    if let selection = self.selection {
        self.avPlayer.replaceCurrentItem(with: AVPlayerItem(url: selection.fileURL))
        self.avPlayer.play()
    }
}

var body: some View {
    if let selection = selection {
        VStack {
            videoPlayer
            
            Spacer()
            Divider()
            
            SessionDescription(session: selection, style: .detailed)
        }
        .padding()
    } else {
        Text("Select a session.")
    }
}

var videoPlayer: some View {
    VideoPlayer(player: self.avPlayer)
        .onAppear {
            self.playCurrentSelection()
        }
        .onDisappear {
            self.avPlayer.pause()
        }
        .onChange(of: selection) { _ in
            self.playCurrentSelection()
        }
        .aspectRatio(16.0 / 9.0, contentMode: .fit)
}

}

struct DetailView_Previews: PreviewProvider { @ObservedObject static var previewSessionManager = PreviewSessionManager()

static var previews: some View {
    DetailView(selection: previewSessionManager.session)
}

}

url: https://developer.apple.com/documentation/backgroundassets/downloading_essential_assets_in_the_background title: Downloading essential assets in the background description: Fetch the assets your app requires before its first launch using an app extension and the Background Assets framework. code_title: SessionDescription.swift code_sample: import Foundation import SwiftUI

struct SessionDescription: View { @ObservedObject var session: LocalSession var style: Style

enum Style {
    case short
    case detailed
}

var body: some View {
    switch self.style {
    case .short:
        shortDescription
    case .detailed:
        detailedDescription
    }
}

var shortDescription: some View {
    VStack(alignment: .leading) {
        HStack {
            Text(session.year.description)
                .font(.subheadline)
                .foregroundStyle(.tertiary)
        }
        Text(session.title)
            .font(.headline)
        Text(session.authors.joined(separator: ", "))
            .font(.callout)
    }
}

var detailedDescription: some View {
    VStack {
        Text(session.title)
            .font(.largeTitle)
            .fontWeight(.bold)
            .frame(maxWidth: .infinity, alignment: .leading)
        Text(session.description)
            .font(.subheadline)
            .frame(maxWidth: .infinity, alignment: .leading)
            .foregroundStyle(.secondary)
        Text(session.authors.joined(separator: ", "))
            .font(.callout)
            .frame(maxWidth: .infinity, alignment: .leading)
    }
}

}

struct SessionDescription_Previews: PreviewProvider { @State static private var sessionManager = SessionManager() static var previews: some View { if let session = sessionManager.sessions.first { VStack { Text("-- Short --") SessionDescription(session: session, style: .short) Text("-- Detailed ---") SessionDescription(session: session, style: .detailed) } } else { ProgressView() } } }

url: https://developer.apple.com/documentation/backgroundassets/downloading_essential_assets_in_the_background title: Downloading essential assets in the background description: Fetch the assets your app requires before its first launch using an app extension and the Background Assets framework.

【5†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

headerFields[.uploadIncomplete] = nil XCTAssertEqual(recorder.receivedFrames[0], HTTPTypeRequestPart.head(expectedRequest)) XCTAssertEqual(recorder.receivedFrames[1], HTTPTypeRequestPart.body(ByteBuffer(string: "He"))) XCTAssertEqual(recorder.receivedFrames[2], HTTPTypeRequestPart.body(ByteBuffer(string: "llo"))) XCTAssertEqual(recorder.receivedFrames[3], HTTPTypeRequestPart.end(nil)) XCTAssertTrue(try channel3.finish().isClean) XCTAssertTrue(try channel.finish().isClean) } }

private extension HTTPField.Name { static let uploadDraftInteropVersion = Self("Upload-Draft-Interop-Version")! static let uploadIncomplete = Self("Upload-Incomplete")! static let uploadOffset = Self("Upload-Offset")! }

url: https://developer.apple.com/documentation/backgroundassets/downloading_essential_assets_in_the_background title: Downloading essential assets in the background description: Fetch the assets your app requires before its first launch using an app extension and the Background Assets framework. code_title: Manifest.swift code_sample: import Foundation

final class Manifest: Codable { public let sessions: [LocalSession] private let sessionsByDownloadIdentifier: [String: LocalSession]

static func load(from fileURL: URL) throws -> Manifest {
    let data = try Data(contentsOf: fileURL, options: .mappedIfSafe)
    let decoder = PropertyListDecoder()
    return try decoder.decode(Manifest.self, from: data)
}

convenience init() {
    self.init(sessions: [])
}

init(sessions: [LocalSession]) {
    self.sessions = sessions
    self.sessionsByDownloadIdentifier = Dictionary(uniqueKeysWithValues: sessions.map { ($0.downloadIdentifier, $0) })
}

func session(for downloadIdentifier: String) -> LocalSession? {
    self.sessionsByDownloadIdentifier[downloadIdentifier]
}

func save(to fileURL: URL) throws {
    let encoder = PropertyListEncoder()
    let data = try encoder.encode(self)
    try data.write(to: fileURL, options: .atomic)
}

// MARK: Codable

private enum CodingKeys: String, CodingKey {
    case sessions
}

convenience init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    let sessions = try container.decode([Session].self, forKey: .sessions)
    
    self.init(sessions: sessions.map {
        LocalSession(session: $0)
    })
}

}

url: https://developer.apple.com/documentation/backgroundassets/downloading_essential_assets_in_the_background title: Downloading essential assets in the background description: Fetch the assets your app requires before its first launch using an app extension and the Background Assets framework. code_title: SharedSettings.swift code_sample: import Foundation

class SharedSettings {

static let appGroupIdentifier = {
    guard let infoDictionary = Bundle.main.infoDictionary,
          let identifier = infoDictionary["AppGroupIdentifier"] as? String else {
        fatalError("Failed to retrieve App Group Identifier from Info.plist.")
    }

    return identifier
}()

static let sharedResourcesURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroupIdentifier)!

【6†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

guard type(of: download) == BAURLDownload.self else { return }

    guard let session = self.manifest.session(for: download.identifier) else {
        Logger.app.warning("Unknown download: \(download.identifier)")
        return
    }
    
    let progress = Double(totalBytesWritten) / Double(totalExpectedBytes)
    updateDownloadProgress(session, progress: progress)
}

func download(_ download: BADownload, finishedWithFileURL fileURL: URL) {
    guard let session = self.manifest.session(for: download.identifier) else {
        Logger.app.warning("Unknown download: \(download.identifier)")
        return
    }
    
    do {
        _ = try FileManager.default.replaceItemAt(session.fileURL, withItemAt: fileURL)
    } catch {
        Logger.app.error("Failed to move downloaded file: \(error)")
        return
    }
    
    Task { @MainActor in
        session.state = .downloaded
        await session.fetchThumbnail()
    }
}

func download(_ download: BADownload, failedWithError error: Error) {
    // If the `BAManifestURL` fails to download, the BADownloadManager's delegate is notified about it.
    // The type of the manifest is not a `BAURLDownload`, therefore you can key off of
    // the download's type to filter it out.
    guard type(of: download) == BAURLDownload.self else {
        Logger.app.warning("Download of unsupported type failed: \(download.identifier). \(error)")
        return
    }

    guard self.manifest.session(for: download.identifier) != nil else {
        Logger.app.warning("Unknown download: \(download.identifier)")
        return
    }
    
    Logger.app.warning("Download failed: \(error)")
}

func download(_ download: BADownload, didReceive challenge: URLAuthenticationChallenge) async
    -> (URLSession.AuthChallengeDisposition, URLCredential?) {
    return (.performDefaultHandling, nil)
}

}

url: https://developer.apple.com/documentation/backgroundassets/downloading_essential_assets_in_the_background title: Downloading essential assets in the background description: Fetch the assets your app requires before its first launch using an app extension and the Background Assets framework. code_title: DetailView.swift code_sample: import Foundation import SwiftUI import AVKit

struct DetailView: View { @Binding var selection: LocalSession? @State private var avPlayer = AVPlayer()

func playCurrentSelection() {
    if let selection = self.selection {
        self.avPlayer.replaceCurrentItem(with: AVPlayerItem(url: selection.fileURL))
        self.avPlayer.play()
    }
}

var body: some View {
    if let selection = selection {
        VStack {
            videoPlayer
            
            Spacer()
            Divider()
            
            SessionDescription(session: selection, style: .detailed)
        }
        .padding()
    } else {
        Text("Select a session.")
    }
}

var videoPlayer: some View {
    VideoPlayer(player: self.avPlayer)
        .onAppear {
            self.playCurrentSelection()
        }
        .onDisappear {
            self.avPlayer.pause()
        }
        .onChange(of: selection) { _ in
            self.playCurrentSelection()
        }
        .aspectRatio(16.0 / 9.0, contentMode: .fit)
}

}

struct DetailView_Previews: PreviewProvider { @ObservedObject static var previewSessionManager = PreviewSessionManager()

static var previews: some View {
    DetailView(selection: previewSessionManager.session)
}

}

url: https://developer.apple.com/documentation/backgroundassets/downloading_essential_assets_in_the_background title: Downloading essential assets in the background description: Fetch the assets your app requires before its first launch using an app extension and the Background Assets framework.

【7†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

= nil @Published var downloadProgress = 0.0 @Published var state: State = .remote

convenience init(session: Session) {
    let fileURL = LocalSession.fileURL(for: session)
    let exists = FileManager.default.fileExists(atPath: fileURL.path(percentEncoded: false))
    let state: State = exists ? .downloaded : .remote
    
    self.init(fileURL: fileURL, session: session, state: state)
}

init(fileURL: URL, session: Session, state: State) {
    self.fileURL = fileURL
    self.thumbnailImage = nil
    self.state = state
    
    super.init(sessionId: session.sessionId,
               title: session.title,
               description: session.description,
               fileSize: session.fileSize,
               authors: session.authors,
               year: session.year,
               thumbnailOffsetInSeconds: session.thumbnailOffsetInSeconds,
               essential: session.essential,
               URL: session.URL)
    
    if self.state != .remote {
        Task {
            await fetchThumbnail()
        }
    }
}

@MainActor
func fetchThumbnail() async {
    let image = await self.generateThumbnail()
    self.thumbnailImage = image
}

func generateThumbnail() async -> CGImage? {
    let asset = AVAsset(url: self.fileURL)
    let imageGenerator = AVAssetImageGenerator(asset: asset)
    
    let time = CMTime(seconds: Double(self.thumbnailOffsetInSeconds), preferredTimescale: 1)
    
    enum ImageGenerationError: Error {
        case noResult
    }
    
    return try? await withCheckedThrowingContinuation({ continuation in
        imageGenerator.generateCGImageAsynchronously(for: time) { image, time, error in
            if let image = image {
                continuation.resume(returning: image)
            } else if let error = error {
                continuation.resume(throwing: error)
            } else {
                continuation.resume(throwing: ImageGenerationError.noResult)
            }
        }
    })
}

public static func fileURL(for session: Session) -> URL {
    return SharedSettings.sessionStorageURL
        .appending(component: "Session_\(session.sessionId)")
        .appendingPathExtension("mp4")
}

// MARK: Decodable

private enum CodingKeys: String, CodingKey {
    case fileURL
}

required init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    self.fileURL = try container.decode(Foundation.URL.self, forKey: .fileURL)
    try super.init(from: decoder)
}

}

url: https://developer.apple.com/documentation/backgroundassets/downloading_essential_assets_in_the_background title: Downloading essential assets in the background description: Fetch the assets your app requires before its first launch using an app extension and the Background Assets framework. code_title: Session.swift code_sample: import Foundation

struct WWDC { enum Year: UInt, Equatable, CaseIterable, CustomStringConvertible, Codable { var description: String { guard let numeric = self.numericRepresentation else { return "WWDC" }

        return "WWDC\(numeric)"
    }
    
    fileprivate var numericRepresentation: UInt?

【8†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

headerFields[.uploadOffset], "2") XCTAssertEqual(try channel2.readOutbound(as: HTTPTypeResponsePart.self), .end(nil)) XCTAssertTrue(try channel2.finish().isClean)

    let channel3 = EmbeddedChannel()
    try channel3.pipeline.addHandler(HTTPResumableUploadHandler(context: context, handlers: [])).wait()
    var request3 = HTTPRequest(method: .patch, scheme: "https", authority: "example.com", path: resumptionPath)
    request3.headerFields[.uploadDraftInteropVersion] = "3"
    request3.headerFields[.uploadIncomplete] = "?0"
    request3.headerFields[.uploadOffset] = "2"
    request3.headerFields[.contentLength] = "3"
    try channel3.writeInbound(HTTPTypeRequestPart.head(request3))
    try channel3.writeInbound(HTTPTypeRequestPart.body(ByteBuffer(string: "llo")))
    try channel3.writeInbound(HTTPTypeRequestPart.end(nil))

    XCTAssertEqual(recorder.receivedFrames.count, 4)
    var expectedRequest = request
    expectedRequest.headerFields[.uploadIncomplete] = nil
    XCTAssertEqual(recorder.receivedFrames[0], HTTPTypeRequestPart.head(expectedRequest))
    XCTAssertEqual(recorder.receivedFrames[1], HTTPTypeRequestPart.body(ByteBuffer(string: "He")))
    XCTAssertEqual(recorder.receivedFrames[2], HTTPTypeRequestPart.body(ByteBuffer(string: "llo")))
    XCTAssertEqual(recorder.receivedFrames[3], HTTPTypeRequestPart.end(nil))
    XCTAssertTrue(try channel3.finish().isClean)
    XCTAssertTrue(try channel.finish().isClean)
}

}

private extension HTTPField.Name { static let uploadDraftInteropVersion = Self("Upload-Draft-Interop-Version")! static let uploadIncomplete = Self("Upload-Incomplete")! static let uploadOffset = Self("Upload-Offset")! }

url: https://developer.apple.com/documentation/backgroundassets/downloading_essential_assets_in_the_background title: Downloading essential assets in the background description: Fetch the assets your app requires before its first launch using an app extension and the Background Assets framework. code_title: Manifest.swift code_sample: import Foundation

final class Manifest: Codable { public let sessions: [LocalSession] private let sessionsByDownloadIdentifier: [String: LocalSession]

static func load(from fileURL: URL) throws -> Manifest {
    let data = try Data(contentsOf: fileURL, options: .mappedIfSafe)
    let decoder = PropertyListDecoder()
    return try decoder.decode(Manifest.self, from: data)
}

convenience init() {
    self.init(sessions: [])
}

init(sessions: [LocalSession]) {
    self.sessions = sessions
    self.sessionsByDownloadIdentifier = Dictionary(uniqueKeysWithValues: sessions.map { ($0.downloadIdentifier, $0) })
}

func session(for downloadIdentifier: String) -> LocalSession?

【9†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

AnimationResource .generate(with: line)

                    child.playAnimation(animation, transitionDuration: 0.0, startsPaused: false)
                    child.playAnimation(child.availableAnimations[0])
                }
            }
        }
    }
}

/// A Boolean value that indicates that game assets have loaded.
var readyToStart = false

// Music players.
var victoryPlayer = try! AVAudioPlayer(contentsOf: Bundle.main.url(forResource: "happyBeamVictory", withExtension: "m4a")!)
var gameplayPlayer = try! AVAudioPlayer(contentsOf: Bundle.main.url(forResource: "happyBeamGameplay", withExtension: "m4a")!)
var menuPlayer = try! AVAudioPlayer(contentsOf: Bundle.main.url(forResource: "happyBeamMenu", withExtension: "m4a")!)

var isSharePlaying = false
var isSpatial = false

var isFinished = false {
    didSet {
        if isFinished == true {
            clear()
            gameplayPlayer.pause()
            
            victoryPlayer.numberOfLoops = -1
            victoryPlayer.volume = 0.6
            victoryPlayer.currentTime = 0
            victoryPlayer.play()
        }
    }
}

var isSoloReady = false {
    didSet {
        if isPlaying == true {
            victoryPlayer.pause()

            gameplayPlayer.volume = 0.6
            gameplayPlayer.currentTime = 0
            gameplayPlayer.play()
        }
    }
}

static let gameTime = 35
var timeLeft = gameTime
var isCountDownReady = false {
    didSet {
        if isCountDownReady == true {
            menuPlayer.setVolume(0, fadeDuration: Double(countDown))
        }
    }
}

var countDown = 3
var score = 0
var isMuted = false {
    didSet {
        if isMuted == true {
            gameplayPlayer.pause()
        } else {
            gameplayPlayer.play()
        }
    }
}
var isInputSelected = false
var inputKind: InputKind = .hands

var players = initialPlayers
var clouds: [Cloud] = (0..<30).map { Cloud(id: $0, isHappy: false) }
var cloudSounds = [AudioFileResource]()

var isUsingControllerInput = false
var controllerX: Float = 0
var controllerY: Float = 90.0
var controllerInputX: Float = 0
var controllerInputY: Float = 0
var controllerLastInput = Date.timeIntervalSinceReferenceDate
var controllerDismissTimer: Timer?

/// Removes 3D content when then game is over.
func clear() {
    spaceOrigin.children.removeAll()
}

/// Resets game state information.

【10†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

self.isExporting = true }

}

nonisolated
func loadImages(from fileURLs: [URL]) -> [Asset] {
    let assets: [Asset] = fileURLs.map { url in
        return Asset.load(from: url)
    }
    return assets
}

nonisolated
func loadPhotos(from items: [PhotosPickerItem]) async -> [Asset] {
    var assets: [Asset] = []
    for item in items {
        do {
            // Get the local identifier to find the corresponding photo asset in the Photos library.
            if let localIdentifier = item.itemIdentifier,
               let data = try await item.loadTransferable(type: Data.self) {
                let asset = Asset.load(from: data, identifier: localIdentifier)
                assets.append(asset)
            }
        } catch {
            print("Failed to load data.")
        }
    }
    return assets
}

func didLoad(_ assets: [Asset]) {
    self.assets.append(contentsOf: assets)
    self.selectedAsset = assets.first
}

func reload(from file: URL) {
    reload(Asset.load(from: file))
}

func reload(from data: Data, identifier: String) {
    reload(Asset.load(from: data, identifier: identifier))
}

func reload(_ asset: Asset?) {
    guard let oldAsset = selectedAsset,
          let newAsset = asset,
          let idx = assets.firstIndex(of: oldAsset)
    else {
        return
    }
    self.assets[idx] = newAsset
    self.selectedAsset = newAsset
}

}

url: https://developer.apple.com/documentation/uikit/images_and_pdf/supporting_hdr_images_in_your_app title: Supporting HDR images in your app description: ​ Load, display, edit, and save HDR images using SwiftUI and Core Image. ​ code_title: Renderer.swift code_sample: import Foundation import CoreImage import CoreVideo import ImageIO import UniformTypeIdentifiers

class Renderer {

let queue = DispatchQueue(label: "render")
let pool: CVPixelBufferPool? = nil
let context = CIContext(options: [.name: "Renderer"])

// Use the image.colorspace as a destination space, if possible.
// CIImages with applied filters may report the .colorspace property as nil
// to indicate that the image is in the Core Image working colorpsace.
// Provide a 'destinationColorspace' to use when this is the case.
func render(_ image: CIImage, destinationColorspace: CGColorSpace?) async -> CVPixelBuffer? {

    let width = Int(image.extent.size.width)
    let height = Int(image.extent.size.height)

    let colorspaceName = String(destinationColorspace?.name ?? "")
    
    return await withUnsafeContinuation { continuation in
        queue.async { [context] in
            let transferFunction: CFString

            if colorspaceName.contains("HLG") {
                transferFunction = kCVImageBufferTransferFunction_ITU_R_2100_HLG
            } else {
                transferFunction = kCVImageBufferTransferFunction_SMPTE_ST_2084_PQ
            }
            
            // Use appropriate CVPixelBuffer options to ensure HDR support.
            let attributes: [CFString: Any] = [
                kCVPixelBufferIOSurfacePropertiesKey: [CFString: Any]() as CFDictionary,
                kCVPixelBufferMetalCompatibilityKey: true as CFNumber
            ]
            var buffer: CVPixelBuffer! = nil
            // Use the memory-efficient HDR-capable pixel format.

【11†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

String else { fatalError("Failed to retrieve App Group Identifier from Info.plist.") }

    return identifier
}()

static let sharedResourcesURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroupIdentifier)!

static let sessionStorageURL = {
    let url = sharedResourcesURL.appending(component: "Sessions", directoryHint: .isDirectory)
    
    do {
        try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
    } catch {
        fatalError("Failed to create session storage directory: \(error)")
    }
    
    return url
}()

static let localManifestURL = sessionStorageURL.appending(path: "manifest.plist")

}

url: https://developer.apple.com/documentation/backgroundassets/downloading_essential_assets_in_the_background title: Downloading essential assets in the background description: Fetch the assets your app requires before its first launch using an app extension and the Background Assets framework. code_title: LocalSession.swift code_sample: import Foundation import SwiftUI import AVFoundation import OSLog

class LocalSession: Session, ObservableObject, Identifiable { enum State: Decodable { case downloaded case remote }

var id = UUID()

var downloadIdentifier: String {
    "SESSION_ID_\(sessionId)"
}

let fileURL: URL
@Published var thumbnailImage: CGImage? = nil
@Published var downloadProgress = 0.0
@Published var state: State = .remote

convenience init(session: Session) {
    let fileURL = LocalSession.fileURL(for: session)
    let exists = FileManager.default.fileExists(atPath: fileURL.path(percentEncoded: false))
    let state: State = exists ? .downloaded : .remote
    
    self.init(fileURL: fileURL, session: session, state: state)
}

init(fileURL: URL, session: Session, state: State) {
    self.fileURL = fileURL
    self.thumbnailImage = nil
    self.state = state
    
    super.init(sessionId: session.sessionId,
               title: session.title,
               description: session.description,
               fileSize: session.fileSize,
               authors: session.authors,
               year: session.year,
               thumbnailOffsetInSeconds: session.thumbnailOffsetInSeconds,
               essential: session.essential,
               URL: session.URL)
    
    if self.state != .remote {
        Task {
            await fetchThumbnail()
        }
    }
}

@MainActor
func fetchThumbnail() async {
    let image = await self.generateThumbnail()
    self.thumbnailImage = image
}

func generateThumbnail() async -> CGImage? {
    let asset = AVAsset(url: self.fileURL)
    let imageGenerator = AVAssetImageGenerator(asset: asset)
    
    let time = CMTime(seconds: Double(self.thumbnailOffsetInSeconds), preferredTimescale: 1)
    
    enum ImageGenerationError: Error {
        case noResult
    }
    
    return try?

【12†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

code_title: VideoSelector.swift code_sample: import SwiftUI

struct VideoSelector: View { @ObservedObject var session: LocalSession var onDelete: () -> Void

var body: some View {
    let selectable = session.state != .remote

    let view = NavigationLink(value: selectable ? session : nil) {
        HStack {
            HStack {
                Thumbnail(localSession: session)
                SessionDescription(session: session, style: .short)
            }
            
            if session.essential {
                Spacer()
                Circle()
                    .fill(.green)
                    .frame(width: 10, alignment: (.trailing))
            }
        }
    }
    .deleteDisabled(session.state != .downloaded)
    #if os(macOS)
    .swipeActions(edge: .trailing) {
        if session.state == .downloaded {
            Button(role: .destructive, action: self.onDelete) {
                Label("Delete", systemImage: "trash")
            }
        }
    }
    #endif

    if selectable {
        view
    } else {
        view.foregroundColor(.gray)
            .disabled(true)
    }
}

}

struct VideoSelector_Previews: PreviewProvider { @State static private var sessionManager = SessionManager()

static var previews: some View {
    NavigationSplitView {
        if let session = sessionManager.sessions.first {
            VideoSelector(session: session) {}
        } else {
            ProgressView()
        }
    } detail: {
        Text("Detail!")
    }
}

}

url: https://developer.apple.com/documentation/backgroundassets/downloading_essential_assets_in_the_background title: Downloading essential assets in the background description: Fetch the assets your app requires before its first launch using an app extension and the Background Assets framework. code_title: VideoSelectorSidebar.swift code_sample: import SwiftUI

struct VideoSelectorSidebar: View { @EnvironmentObject var sessionManager: SessionManager @Binding var selections: Set

var body: some View {
    List(selection: $selections) {
        selectors
    }
    .toolbar(content: toolbarContent)
    #if os(macOS)
    .navigationSplitViewColumnWidth(ideal: 360)
    #endif
}

var selectors: some View {
    ForEach(self.sessionManager.sessions) { session in
        VideoSelector(session: session) {
            self.delete(session: session)
        }
    }
    #if os(iOS)
    .onDelete { indices in
        let sessions = indices.map { self.sessionManager.sessions[$0] }
        for session in sessions {
            self.delete(session: session)
        }
    }
    #endif
}

private func delete(session: LocalSession) {
    self.selections.remove(session)
    self.sessionManager.delete(session)
}

@ToolbarContentBuilder
private func toolbarContent() -> some ToolbarContent {
    #if os(iOS)
    ToolbarItemGroup(placement: .navigationBarTrailing) {
        refreshButton
    }
    #else
    ToolbarItemGroup(placement: .navigation) {
        refreshButton
    }
    #endif
}

var refreshButton: some View {
    Button {
        self.sessionManager.refreshManifest()
    } label: {
        Label("Refresh", systemImage: "arrow.counterclockwise")
    }
}

}

struct VideoSelectorSidebar_Previews: PreviewProvider { struct Preview: View { @State private var selections: Set = [] @StateObject private var sessionManager = SessionManager()

    var body: some View {
        VideoSelectorSidebar(selections: $selections)
            .environmentObject(sessionManager)
    }
}

static var previews: some View {
    NavigationSplitView {
        Preview()
    } detail: {
        Text("Detail!")

【13†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

} } }

url: https://developer.apple.com/documentation/backgroundassets/downloading_essential_assets_in_the_background title: Downloading essential assets in the background description: Fetch the assets your app requires before its first launch using an app extension and the Background Assets framework. code_title: BackgroundDownloadHandler.swift code_sample: import BackgroundAssets import OSLog

public extension Logger { static let ext = Logger(subsystem: "com.example.apple-samplecode.WWDC-Sessions", category: "extension") }

@main struct BackgroundDownloadHandler: BADownloaderExtension {

func downloads(for request: BAContentRequest,
               manifestURL: URL,
               extensionInfo: BAAppExtensionInfo) -> Set<BADownload> {
    
    let manifest: Manifest
    do {
        // Load the downloaded manifest and parse it to ensure its validity
        // Keep in mind that the `manifestURL` is read-only, and will be
        // deleted once this function exits scope.
        manifest = try Manifest.load(from: manifestURL)
        
        // Atomically save the parsed manifest to its final location
        // Note: Since this function performs an atomic replace, acquiring
        // exclusive control is not necessary
        try manifest.save(to: SharedSettings.localManifestURL)
        
    } catch {
        Logger.ext.error("Failed to load and replace manifest: \(error)")
        return []
    }
    
    // Essential downloads contribute to app installation progress, and
    // download with foreground priority. Therefore they are only enqueuable
    // during app-install or app-update.
    let essentialDownloadsPermitted = request == .install || request == .update
    
    // The final set of downloads to be scheduled.
    var downloadsToSchedule: Set<BADownload> = []
    
    // Iterate through the new manifest, enqueueing downloads for any sessions
    // that are not already present on the device.
    for session in manifest.sessions where session.state == .remote {
        let download = BAURLDownload(
            identifier: session.downloadIdentifier,
            request: URLRequest(url: session.URL),
            essential: session.essential && essentialDownloadsPermitted,
            fileSize: Int(session.fileSize),
            applicationGroupIdentifier: SharedSettings.appGroupIdentifier,
            priority: .default)
        
        Logger.ext.log("Enqueued download: \(download.identifier)")
        downloadsToSchedule.insert(download)
    }
    
    return downloadsToSchedule
}

func backgroundDownload(_ failedDownload: BADownload, failedWithError error: Error) {
    // If the `BAManifestURL` fails to download, the extension is notified about it.
    // The type of the manifest is not a `BAURLDownload`, therefore you can key off of
    // the download's type to filter it out.
    guard type(of: failedDownload) == BAURLDownload.self else {
        Logger.ext.warning("Download of unsupported type failed: \(failedDownload.identifier). \(error)")
        return
    }
    
    // If the failed download is essential, it can be re-enqueued in the background
    // so that it may be downloaded at a later point in time.
    if failedDownload.isEssential {
        Logger.ext.warning("Rescheduling failed download: \(failedDownload.identifier). \(error)")
        do {
            let optionalDownload = failedDownload.removingEssential()
            try BADownloadManager.shared.scheduleDownload(optionalDownload)
        } catch {
            Logger.ext.warning("Failed to reschedule download \(failedDownload.identifier). \(error)")
        }
    } else {
        Logger.ext.warning("Download failed: \(failedDownload.identifier).

【14†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

.library( name: "RealityKit-Assets", targets: ["RealityKit-Assets"]) ], dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages this package depends on. .target( name: "RealityKit-Assets", dependencies: []) ] )

url: https://developer.apple.com/documentation/realitykit/rendering-a-windowed-game-in-stereo title: Rendering a windowed game in stereo description: Bring an iOS or iPadOS game to visionOS and enhance it. code_title: RealityKit-Assets.swift code_sample: import Foundation

/// Bundle for the RealityKit-Assets project. public let assetsBundle = Bundle.module

url: https://developer.apple.com/documentation/realitykit/rendering-a-windowed-game-in-stereo title: Rendering a windowed game in stereo description: Bring an iOS or iPadOS game to visionOS and enhance it. code_title: HeadTracker.swift code_sample: import SwiftUI import RealityKit import ARKit import Spatial

extension AffineTransform3D { var float4x4: simd_float4x4 { return simd_float4x4(matrix4x4) } }

@MainActor class HeadPositionProvider: ObservableObject { let arSession = ARKitSession() let worldTracking = WorldTrackingProvider() var coordinateConverter: RealityCoordinateSpaceConverting?

init() {
}

func start() {
    Task {
        do {
            if WorldTrackingProvider.isSupported {
                try await arSession.run([worldTracking])
            }
        } catch let error as ARKitSession.Error {
            print("Encountered an error while running providers: \(error.localizedDescription)")
        } catch let error {
            print("Encountered an unexpected error: \(error.localizedDescription)")
        }
    }
}

func stop() {

}

var presentationTime: CFTimeInterval {
    // Estimate for presentation time. This sample renders at 90 Hz, so estimate
    // two additional frames in the future.
    return CACurrentMediaTime() + 0.033
}

var originFromHead: simd_float4x4? {
    self.originFromDeviceTransform(presentationTime)
}

private func originFromDeviceTransform(_ time: CFTimeInterval) -> simd_float4x4? {
    guard let devicePose = worldTracking.queryDeviceAnchor(atTimestamp: time) ??
            worldTracking.queryDeviceAnchor(atTimestamp: CACurrentMediaTime()) else {
        return nil
    }

    return devicePose.originFromAnchorTransform
}

}

url: https://developer.apple.com/documentation/realitykit/rendering-a-windowed-game-in-stereo title: Rendering a windowed game in stereo description: Bring an iOS or iPadOS game to visionOS and enhance it. code_title: LazyAsync.swift code_sample: public actor LazyAsync {

private var value: T?
private let closure: () async -> T

public init(_ closure: @escaping () async -> T) {
    self.closure = closure
}

public func get() async -> T {
    if let value = value {
        return value
    } else {
        self.value = await closure()
        return await get()
    }
}

}

url: https://developer.apple.com/documentation/realitykit/rendering-a-windowed-game-in-stereo title: Rendering a windowed game in stereo description: Bring an iOS or iPadOS game to visionOS and enhance it.

【15†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

code_title: Thumbnail.swift code_sample: import SwiftUI

let thumbnailWidth: CGFloat = 96.0 let thumbnailHeight = CGFloat(thumbnailWidth) / (16.0 / 9.0)

struct Thumbnail: View { @ObservedObject var localSession: LocalSession

var body: some View {
    if localSession.state == .remote {
        ProgressView(value: localSession.downloadProgress)
            .progressViewStyle(GaugeProgressStyle())
            .frame(width: thumbnailWidth, height: thumbnailHeight)
    } else if let image = localSession.thumbnailImage {
        Image(image, scale: 1.0, label: Text("Thumbnail image for developer session video."))
            .resizable()
            .aspectRatio(16.0 / 9.0, contentMode: .fit)
            .frame(width: thumbnailWidth)
            .clipShape(RoundedRectangle(cornerRadius: 8.0))
    } else {
        ProgressView()
            .frame(width: thumbnailWidth, height: thumbnailHeight)
    }
}

struct GaugeProgressStyle: ProgressViewStyle {
    let strokeColor = Color(white: 0)
    let strokeWidth = 6.0

    public func makeBody(configuration: Configuration) -> some View {
        let fractionCompleted = configuration.fractionCompleted ?? 0

        return Circle()
            .fill(Color(white: 0.85,
                        opacity: 0.85))
            .frame(width: 30, height: 30)
            .overlay {
                ZStack {
                    Circle()
                        .trim(from: 0, to: CGFloat(fractionCompleted))
                        .stroke(strokeColor, style: StrokeStyle(lineWidth: CGFloat(strokeWidth), lineCap: .round))
                        .rotationEffect(.degrees(-90))
                        .frame(width: 20, height: 20)
                        .animation(.linear, value: fractionCompleted)
                }
            }
    }
}

}

struct Thumbnail_Previews: PreviewProvider { @State static var sessionManager = SessionManager()

static var previews: some View {
    if let session = sessionManager.sessions.first {
        Thumbnail(localSession: session)
    } else {
        ProgressView()
    }
}

}

url: https://developer.apple.com/documentation/backgroundassets/downloading_essential_assets_in_the_background title: Downloading essential assets in the background description: Fetch the assets your app requires before its first launch using an app extension and the Background Assets framework. code_title: VideoSelector.swift code_sample: import SwiftUI

struct VideoSelector: View { @ObservedObject var session: LocalSession var onDelete: () -> Void

var body: some View {
    let selectable = session.state != .remote

    let view = NavigationLink(value: selectable ?

【16†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

await Entity(named: "TrailPath_Export/TrailPath_Export.usdc", in: RealityKitContentBundle) { content.add(root) root.findEntity(named: "Catalina_TrailA")?.components.set(TrailComponent())

    }
}
.previewLayout(.sizeThatFits)

}

url: https://developer.apple.com/documentation/visionos/diorama title: Diorama description: Design scenes for your visionOS app using Reality Composer Pro. code_title: TrailComponent.swift code_sample: import RealityKit

// Ensure you register this component in your app’s delegate using: // TrailComponent.registerComponent() /// A component that marks an entity as a trail. Make sure you register this component in your app /// delegate using RegionSpecificComponent.registerComponent() public struct TrailComponent: Component, Codable {

public init() {
}

}

url: https://developer.apple.com/documentation/visionos/swift-splash title: Swift Splash description: Use RealityKit to create an interactive ride in visionOS. code_title: Package.swift code_sample: // swift-tools-version: 6.0 /* See the LICENSE.txt file for this sample’s licensing information.

Abstract: A package that contains model assets. */ import PackageDescription

let package = Package( name: "SwiftSplashTrackPieces", platforms: [ .visionOS(.v2) ], products: [ .library( name: "SwiftSplashTrackPieces", targets: ["SwiftSplashTrackPieces"] ) ], dependencies: [], targets: [ .target( name: "SwiftSplashTrackPieces", dependencies: [] ) ] )

url: https://developer.apple.com/documentation/visionos/swift-splash title: Swift Splash description: Use RealityKit to create an interactive ride in visionOS.

【17†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

public func loadPieces() async { defer { finishedLoadingAssets() } let startTime = Date.timeIntervalSinceReferenceDate logger.info("Starting load from Reality Composer Pro Project.") finishedStartingUp() await withTaskGroup(of: LoadResult.self) { taskGroup in loadTrackPieces(taskGroup: &taskGroup) loadStartPiece(taskGroup: &taskGroup) loadGoalPiece(taskGroup: &taskGroup) loadPlacementMarker(taskGroup: &taskGroup) for await result in taskGroup { if let pieceKey = pieces.first(where: { $0.key.rawValue == result.key }) { processLoadedTrackPiece(result: result, pieceKey: pieceKey) } else { if result.key == startPieceName { processLoadedStartPiece(result: result) } else if result.key == endPieceName { processLoadedGoalPiece(result: result) } else if result.key == placePieceMarkerName { self.placePieceMarker = result.entity self.updateMarkerPosition() } } } logger.info("Load of pieces completed. Duration: (Date.timeIntervalSinceReferenceDate - startTime)") } }

/// This function sets up the regular track pieces after load.
private func processLoadedTrackPiece(result: LoadResult, pieceKey: Piece) {
    self.add(template: result.entity, for: pieceKey.key)
    setupConnectable(entity: result.entity)
    result.entity.components.set(HoverEffectComponent())
    result.entity.setUpAnimationVisibility()
    handleTrackPieceTransparency(result.entity)
    result.entity.setWaterLevel(level: 0)
    result.entity.adjustCollisionBox(scaleBy: [1.0, 0.5, 1.0], offsetBy: [0, 0, 0])
}

/// This function sets up the start piece after load.
private func processLoadedStartPiece(result: LoadResult) {
    self.setStartPiece(result.entity)
    result.entity.setWaterLevel(level: 0)
    result.entity.setUpAnimationVisibility()
    result.entity.components.set(HoverEffectComponent())
    setStartPiece(result.entity)
    setStartPieceInitialPosition()
    setupConnectable(entity: result.entity)
    result.entity.playIdleAnimations()
    handleStartPieceTransparency(result.entity)
    result.entity.adjustCollisionBox(scaleBy: [1.0, 0.9, 0.8], offsetBy: [0, 0.1, 0.038])
    
    self.placeMarker(at: result.entity)
    result.entity.connectableStateComponent?.isSelected = false
    clearSelection()
    updateSelection()
}

/// This function sets up the goal piece after load.
private func processLoadedGoalPiece(result: LoadResult) {
    self.setGoalPiece(result.entity)
    setupConnectable(entity: result.entity)
    result.entity.components.set(HoverEffectComponent())
    setGoalPiece(result.entity)
    result.entity.setUpAnimationVisibility()
    result.entity.setWaterLevel(level: 0)
    handleEndPieceTransparency(result.entity)
    result.entity.adjustCollisionBox(scaleBy: [0.95, 0.485, 0.8], offsetBy: [0, 0.11, -0.045])
}

/// This function loads the regular track pieces (everything except the start and end piece and the placement marker).
private func loadTrackPieces(taskGroup: inout TaskGroup<LoadResult>) {
    // Load the regular track pieces and ride animations.
    logger.info("Loading track pieces.")

【18†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

turret = await loadFromRealityComposerPro(named: BundleAssets.heartTurretEntity, fromSceneNamed: BundleAssets.heartTurretScene) turret?.name = "Holder" turret?.position = .init(x: 0, y: 0.25, z: -1.7) turret?.scale *= 0.3

        heart = await loadFromRealityComposerPro(named: BundleAssets.heartLightEntity, fromSceneNamed: BundleAssets.heartLightScene)
        heart?.name = "Heart Projector"
        heart?.generateCollisionShapes(recursive: true)
        heart?.position = .init(x: 0, y: 0.25, z: -1.7)
        heart?.position.y += 0.68
        heart?.scale *= 0.22
        heart?.components[InputTargetComponent.self] = InputTargetComponent(allowedInputTypes: .all)
        
        cloudTemplate = try? await Entity(named: BundleAssets.cloud)
        
        guard turret != nil, heart != nil, cloudTemplate != nil else {
            fatalError("Error loading assets.")
        }
        
        do {
            for number in 1...4 {
                let resource = try await AudioFileResource(named: "cloudHit\(number).m4a")
                cloudSounds.append(resource)
            }
        } catch {
            fatalError("Error loading cloud sound resources.")
        }
        
        // Generate animations inside the cloud models.
        let def = cloudTemplate!.availableAnimations[0].definition
        cloudAnimations[.sadBlink] = try .generate(with: AnimationView(source: def, trimStart: 1.0, trimEnd: 7.0))
        cloudAnimations[.smile] = try .generate(with: AnimationView(source: def, trimStart: 7.5, trimEnd: 10.0))
        cloudAnimations[.happyBlink] = try .generate(with: AnimationView(source: def, trimStart: 10.0, trimEnd: 15.0))
        
        generateCloudMovementAnimations()
        
        self.readyToStart = true
    }
}

/// Preload animation assets.
func generateCloudMovementAnimations() {
    for index in (0..<cloudPaths.count) {
        let start = Point3D(
            x: cloudPaths[index].0,
            y: cloudPaths[index].1,
            z: cloudPaths[index].2
        )
        let end = Point3D(
            x: start.x + CloudSpawnParameters.deltaX,
            y: start.y + CloudSpawnParameters.deltaY,
            z: start.z + CloudSpawnParameters.deltaZ
        )
        let speed = CloudSpawnParameters.speed
        
        let line = FromToByAnimation<Transform>(
            name: "line",
            from: .init(scale: .init(repeating: 1), translation: simd_float(start.vector)),
            to: .init(scale: .init(repeating: 1), translation: simd_float(end.vector)),
            duration: speed,
            bindTarget: .transform
        )
        
        let animation = try! AnimationResource
            .generate(with: line)
        
        cloudMovementAnimations.append(animation)
    }
}

}

/// The kinds of input selections offered to players. enum InputKind { /// An input method that uses ARKit to detect a heart gesture. case hands

/// An input method that spawns a stationary heart projector.
case alternative

}

url: https://developer.apple.com/documentation/visionos/happybeam title: Happy Beam description: Leverage a Full Space to create a fun game using ARKit. code_title: GlobalEntities.swift code_sample: import RealityKit

/// The root entity for entities placed during the game.

【19†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

code_title: Album.swift code_sample: import Foundation import Photos

@Observable final class Album {

// MARK: Properties

let collection: PHAssetCollection

var title: String
var assets = [Asset]()

var creationDate: Date? {
    collection.startDate
}

// MARK: Lifecycle

init(collection: PHAssetCollection) {
    self.collection = collection
    self.title = collection.localizedTitle ?? ""
}

// MARK: Methods

func setTitle(_ title: String) async throws {
    try await PHPhotoLibrary.shared().performChanges {
        let request = PHAssetCollectionChangeRequest(for: self.collection)
        request?.title = title
    }
    self.title = title
}

func setAssets(_ assets: Set<Asset>) async throws {
    let current = Set(self.assets)

    let toInsert = assets.subtracting(current).map(\.phAsset)
    let toRemove = current.subtracting(assets).map(\.phAsset)

    try await PHPhotoLibrary.shared().performChanges {
        let request = PHAssetCollectionChangeRequest(for: self.collection)
        request?.addAssets(toInsert as NSFastEnumeration)
        request?.removeAssets(toRemove as NSFastEnumeration)
    }
    self.assets = Array(assets)
}

func fetchAssets() async throws {
    // Fetch all assets from this collection.
    let fetchResult = PHAsset.fetchAssets(in: collection, options: nil)

    // Enumerate and insert assets.
    var phAssets = [PHAsset]()
    fetchResult.enumerateObjects { (object, count, stop) in
        phAssets.append(object)
    }

    // Process the assets.
    let assets = phAssets.map { phAsset in
        Asset(phAsset: phAsset)
    }

    // Update the assets on the main thread.
    await MainActor.run {
        self.assets = assets
    }
}

}

extension Album: Identifiable, Hashable {

var id: String {
    collection.localIdentifier
}

func hash(into hasher: inout Hasher) {
    hasher.combine(id)
}

static func == (lhs: Album, rhs: Album) -> Bool {
    lhs.id == rhs.id
}

}

extension Album: @unchecked Sendable {

var entity: AlbumEntity {
    let entity = AlbumEntity(id: id)
    entity.name = title
    entity.albumType = .custom
    entity.creationDate = creationDate
    return entity
}

}

url: https://developer.apple.com/documentation/appintents/making-your-app-s-functionality-available-to-siri title: Making your app’s functionality available to Siri description: Add assistant schemas to your app and integrate your app with Siri and Apple Intelligence, and support system experiences like Spotlight. code_title: Asset.swift code_sample: import Foundation import CoreLocation import CoreSpotlight import CoreTransferable import Photos

@Observable final class Asset {

// MARK: Static

static let dateFormatter: DateFormatter = {
    let dateFormatter = DateFormatter()
    dateFormatter.dateStyle = .long
    dateFormatter.timeStyle = .short
    return dateFormatter
}()

// MARK: Properties

let phAsset: PHAsset

var placemark: CLPlacemark?
var isFavorite = false
var isHidden = false

var title: String {
    guard let placemark, let locality = placemark.locality else {
        return Self.dateFormatter.string(from: creationDate ?? .now)
    }

    return locality
}

var creationDate: Date?

Visible: 0% - 100%To preload assets in a visionOS application, you can use the following code snippet that demonstrates how to load various assets asynchronously when the application initializes. This approach helps avoid pop-in during the game by ensuring that assets are preloaded and ready for use.

import RealityKit
import AVFoundation

class GameManager {
    var beam: Entity!
    var floorBeam: Entity!
    var globalFireworks: Entity!
    var turret: Entity!
    var heart: Entity!
    var cloudTemplate: Entity!
    var cloudSounds: [AudioFileResource] = []

    init() {
        Task { @MainActor in
            guard let beamAsset = await loadFromRealityComposerPro(
                named: "heartBlasterEntity",
                fromSceneNamed: "heartBlasterScene"
            ) else {
                fatalError("Unable to load beam from Reality Composer Pro project.")
            }
            beam = beamAsset
            beam.name = "beam"
            beam.position = .init(x: 0, y: 0, z: -0.3)
            beam.orientation = simd_quatf(
                Rotation3D(angle: .degrees(90), axis: .y)
                    .rotated(by: Rotation3D(angle: .degrees(-90), axis: .z))
            )
            
            floorBeam = beam.clone(recursive: true)
            floorBeam.name = "floorBeam"
            floorBeam.position.z += 0.3
            
            let fireworks = try await Entity(named: "fireworks")
            globalFireworks = fireworks.children.first!.children.first!
            
            turret = await loadFromRealityComposerPro(named: "heartTurretEntity", fromSceneNamed: "heartTurretScene")
            turret?.name = "Holder"
            turret?.position = .init(x: 0, y: 0.25, z: -1.7)
            turret?.scale *= 0.3
            
            heart = await loadFromRealityComposerPro(named: "heartLightEntity", fromSceneNamed: "heartLightScene")
            heart?.name = "Heart Projector"
            heart?.generateCollisionShapes(recursive: true)
            heart?.position = .init(x: 0, y: 0.25, z: -1.7)
            heart?.position.y += 0.68
            heart?.scale *= 0.22
            heart?.components[InputTargetComponent.self] = InputTargetComponent(allowedInputTypes: .all)
            
            cloudTemplate = try? await Entity(named: "cloud")
            
            guard turret != nil, heart != nil, cloudTemplate != nil else {
                fatalError("Error loading assets.")
            }
            
            do {
                for number in 1...4 {
                    let resource = try await AudioFileResource(named: "cloudHit\(number).m4a")
                    cloudSounds.append(resource)
                }
            } catch {
                fatalError("Error loading cloud sound resources.")
            }
        }
    }

    private func loadFromRealityComposerPro(named entityName: String, fromSceneNamed sceneName: String) async -> Entity? {
        // Custom function to load entities from Reality Composer Pro
        // Implement this according to your project's specifics
        return nil
    }
}

In this example, the init() method of GameManager class asynchronously loads several entities and audio resources from Reality Composer Pro and other sources. This ensures that all necessary assets are preloaded before they are needed during gameplay, helping to prevent any delays or pop-in effects.

For more information and detailed guidance on downloading essential assets in the background, refer to Apple's documentation on downloading essential assets in the background【11:0†source】.Is Background Assets relevant for the latency of audio files that are bundled into the app?No, Background Assets are not directly relevant for the latency of audio files that are bundled into the app. Background Assets are typically used for downloading and managing large or additional resources that your app might need after the initial installation, such as updates or new content. These are not intended for managing latency issues for assets already included in the app bundle.

For reducing latency of audio files that are bundled with your app, consider the following approaches:

  1. Preload Audio Files: Preload audio files into memory during the app initialization. This ensures that the audio files are readily available when needed and reduces latency.

  2. Optimize Audio File Formats: Use appropriate audio file formats and compression methods to reduce file size without compromising quality. Smaller files load faster and reduce latency.

  3. Efficient Audio Handling: Utilize efficient audio handling APIs and frameworks provided by Apple, such as AVAudioPlayer or AVAudioEngine, to manage and play audio files with minimal latency.

  4. Background Thread Loading: Load audio files on a background thread to avoid blocking the main thread, ensuring smooth performance and reducing any potential delays when accessing audio files.

Here is an example of how to preload audio files using AVAudioPlayer in Swift:

import AVFoundation

class AudioManager {
    var audioPlayer: AVAudioPlayer?

    init() {
        preloadAudioFiles()
    }

    private func preloadAudioFiles() {
        guard let audioURL = Bundle.main.url(forResource: "audioFileName", withExtension: "m4a") else {
            print("Audio file not found")
            return
        }
        
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: audioURL)
            audioPlayer?.prepareToPlay() // Preloads the audio file into memory
        } catch {
            print("Error loading audio file: \(error)")
        }
    }

    func playAudio() {
        audioPlayer?.play()
    }
}

In this example, the AudioManager class preloads an audio file into memory during initialization by using the prepareToPlay() method of AVAudioPlayer, which reduces latency when the playAudio() method is called.

By preloading your audio files and ensuring efficient handling within your app, you can minimize latency and ensure a smoother audio experience for users.In a visionOs app, where is the best place to put preloading code?In a visionOS app, the best place to put preloading code is typically within the initialization phase of your app. This can be done in the App struct or the main entry point of your app where you set up your environment and scenes. Specifically, you should preload assets early in the app lifecycle to ensure they are ready when needed, reducing latency and ensuring smooth user experience.

Here is a detailed example of where and how to implement preloading code in a visionOS app:

  1. App Entry Point: Use the main App struct to initialize and preload assets when the app launches.

  2. Environment Setup: Create a manager class or a singleton to handle the asset preloading logic.

Here is an example implementation:

1. Create an AssetManager for Preloading

import SwiftUI
import RealityKit
import AVFoundation

class AssetManager: ObservableObject {
    static let shared = AssetManager()
    
    @Published var isReady = false
    
    var beam: Entity!
    var floorBeam: Entity!
    var globalFireworks: Entity!
    var turret: Entity!
    var heart: Entity!
    var cloudTemplate: Entity!
    var cloudSounds: [AudioFileResource] = []

    private init() {
        preloadAssets()
    }
    
    private func preloadAssets() {
        Task { @MainActor in
            do {
                guard let beamAsset = await loadFromRealityComposerPro(named: "heartBlasterEntity", fromSceneNamed: "heartBlasterScene") else {
                    fatalError("Unable to load beam from Reality Composer Pro project.")
                }
                beam = beamAsset
                beam.name = "beam"
                beam.position = .init(x: 0, y: 0, z: -0.3)
                beam.orientation = simd_quatf(
                    Rotation3D(angle: .degrees(90), axis: .y)
                        .rotated(by: Rotation3D(angle: .degrees(-90), axis: .z))
                )
                
                floorBeam = beam.clone(recursive: true)
                floorBeam.name = "floorBeam"
                floorBeam.position.z += 0.3
                
                let fireworks = try await Entity(named: "fireworks")
                globalFireworks = fireworks.children.first!.children.first!
                
                turret = await loadFromRealityComposerPro(named: "heartTurretEntity", fromSceneNamed: "heartTurretScene")
                turret?.name = "Holder"
                turret?.position = .init(x: 0, y: 0.25, z: -1.7)
                turret?.scale *= 0.3
                
                heart = await loadFromRealityComposerPro(named: "heartLightEntity", fromSceneNamed: "heartLightScene")
                heart?.name = "Heart Projector"
                heart?.generateCollisionShapes(recursive: true)
                heart?.position = .init(x: 0, y: 0.25, z: -1.7)
                heart?.position.y += 0.68
                heart?.scale *= 0.22
                heart?.components[InputTargetComponent.self] = InputTargetComponent(allowedInputTypes: .all)
                
                cloudTemplate = try? await Entity(named: "cloud")
                
                guard turret != nil, heart != nil, cloudTemplate != nil else {
                    fatalError("Error loading assets.")
                }
                
                for number in 1...4 {
                    let resource = try await AudioFileResource(named: "cloudHit\(number).m4a")
                    cloudSounds.append(resource)
                }
                
                isReady = true
            } catch {
                fatalError("Error loading assets: \(error)")
            }
        }
    }

    private func loadFromRealityComposerPro(named entityName: String, fromSceneNamed sceneName: String) async -> Entity? {
        // Custom function to load entities from Reality Composer Pro
        // Implement this according to your project's specifics
        return nil
    }
}

2. Initialize AssetManager in the App Entry Point

import SwiftUI

@main
struct MyVisionOSApp: App {
    @StateObject private var assetManager = AssetManager.shared
    
    var body: some Scene {
        WindowGroup {
            ContentView()
                .environmentObject(assetManager)
                .onAppear {
                    assetManager.preloadAssets()
                }
        }
    }
}

3. Use Preloaded Assets in Your Views

import SwiftUI

struct ContentView: View {
    @EnvironmentObject var assetManager: AssetManager
    
    var body: some View {
        VStack {
            if assetManager.isReady {
                // Use preloaded assets here
                Text("Assets Loaded")
            } else {
                Text("Loading Assets...")
            }
        }
    }
}

In this setup:

  • AssetManager: Manages the preloading of assets and is shared across the app using the singleton pattern.
  • MyVisionOSApp: Initializes the AssetManager and ensures assets are preloaded when the app appears.
  • ContentView: Checks if assets are ready and updates the UI accordingly.

By placing the preloading code in the AssetManager and initializing it in the app's entry point, you ensure that assets are preloaded early in the app lifecycle, reducing latency and providing a smooth user experience.

Preload Assets in visionOS created at Tue Jan 20 1970 21:25:32 GMT+0000 (Coordinated Universal Time)

Related Chats

MultipeerManager Error Fix 0.962

Reusable SwiftUI custom view. 0.909

Immersive View Phases 0.900

Handling App Exit 0.898

SwiftUI RealityKit Integration 0.887

Animate Using withAnimation 0.881

Switch to guard statement 0.864

Calculate pointC using SIMD3 0.817

Shared ViewModel Across Views 0.795