Handling App Exit

TODO: collapasable, copyable, download, etc

What is important in my SwiftUI RealityKit app to "exit" the app? 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(["exit app RealityKit SwiftUI"])# 【0†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】 code_title: SplashScreenView.swift code_sample: import RealityKit import SwiftUI

struct SplashScreenView: View { private static let startButtonWidth: CGFloat = 150

@Environment(\.setMode) var setMode

var body: some View {
    ZStack {
        SplashScreenBackgroundView()
        
        VStack {
            Spacer(minLength: 100)
            
            SplashScreenForegroundView()
            
            Spacer(minLength: 50)
            
            Button {
                Task {
                    await setMode(.chooseWorkVolume)
                }
            } label: {
                Text("Start").frame(minWidth: Self.startButtonWidth)
            }
            .glassBackgroundEffect()
            .controlSize(.extraLarge)
            .frame(width: Self.startButtonWidth)
            
            Spacer(minLength: 100)
        }
        .frame(depth: 0, alignment: DepthAlignment.back)
    }
    .frame(depth: 100, alignment: DepthAlignment.back)
}

}

url: https://developer.apple.com/documentation/realitykit/creating-a-spatial-drawing-app-with-realitykit title: Creating a spatial drawing app with RealityKit description: Use low-level mesh and texture APIs to achieve fast updates to a person’s brush strokes by integrating RealityKit with ARKit and SwiftUI. code_title: BrushState.swift code_sample: enum BrushPreset: Equatable { case solid(settings: SolidBrushStyleProvider.Settings)

case sparkle(settings: SparkleBrushStyleProvider.Settings)

}

enum BrushType: Hashable, Equatable, CaseIterable, Identifiable { case uniform

case calligraphic

case sparkle

var id: Self { return self }

var label: String {
    switch self {
    case .calligraphic: return "Calligraphic"
    case .uniform: return "Uniform"
    case .sparkle: return "Sparkle"
    }
}

}

@Observable class BrushState { /// Type of brush being used. var brushType: BrushType = .uniform

/// Style settings for the uniform brush type.
var uniformStyleSettings = SolidBrushStyleProvider.Settings(thicknessType: .uniform)

/// Style settings for the calligraphic brush type.
var calligraphicStyleSettings = SolidBrushStyleProvider.Settings(thicknessType: .calligraphic())

/// Style settings for the sparkle brush type.
var sparkleStyleSettings = SparkleBrushStyleProvider.Settings()

init() {}

init(preset: BrushPreset) { apply(preset: preset) }

var asPreset: BrushPreset {
    switch brushType {
    case .uniform: .solid(settings: uniformStyleSettings)
    case .calligraphic: .solid(settings: calligraphicStyleSettings)
    case .sparkle: .sparkle(settings: sparkleStyleSettings)
    }
}

func apply(preset: BrushPreset) {
    switch preset {
    case let .solid(settings):
        switch settings.thicknessType {
        case .uniform:
            brushType = .uniform
            uniformStyleSettings = settings
        case .calligraphic(_, _, _):
            brushType = .calligraphic
            calligraphicStyleSettings = settings
        }
    case let .sparkle(settings):
        brushType = .sparkle
        sparkleStyleSettings = settings
    }
}

}

url: https://developer.apple.com/documentation/realitykit/creating-a-spatial-drawing-app-with-realitykit title: Creating a spatial drawing app with RealityKit description: Use low-level mesh and texture APIs to achieve fast updates to a person’s brush strokes by integrating RealityKit with ARKit and SwiftUI.

【1†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

code_title: AppModel.swift code_sample: import SwiftUI

// Maintains an app-wide state. @Observable public class AppModel { public var showImmersiveSpace = false public var immersiveSpaceIsShown = false }

url: https://developer.apple.com/documentation/realitykit/composing-interactive-3d-content-with-realitykit-and-reality-composer-pro title: Composing interactive 3D content with RealityKit and Reality Composer Pro description: Build an interactive scene using an animation timeline. code_title: ContentView.swift code_sample: import SwiftUI import RealityKit import RealityKitContent

struct ContentView: View {

@State private var enlarge = false

@Environment(\.scenePhase) private var scenePhase
@Environment(\.dismissImmersiveSpace) var dismissImmersiveSpace
@Environment(AppModel.self) var appModel

var body: some View {
    RealityView { content in
        // Add the initial RealityKit content.

        // Register custom components and systems the app uses.
        HeroPlantComponent.registerComponent()
        HeroPlantSystem.registerSystem()
        StationaryRobotComponent.registerComponent()
        StationaryRobotSystem.registerSystem()
        HeroRobotComponent.registerComponent()
        HeroRobotSystem.registerSystem()
        EntityMoverComponent.registerComponent()
        EntityMoverSystem.registerSystem()

        if let scene = try? await Entity(named: "Scene", in: realityKitContentBundle) {
            content.add(scene)
        }
    } update: { content in
        // Update the RealityKit content when SwiftUI state changes.
        if let scene = content.entities.first {
            let uniformScale: Float = enlarge ? 1.4 : 1.0
            scene.transform.scale = [uniformScale, uniformScale, uniformScale]
        }
    }
    .onChange(of: scenePhase) { _, newPhase in
        Task { @MainActor in
            if newPhase == .background {
                appModel.showImmersiveSpace = false
            }
        }
    }
    .gesture(TapGesture().targetedToAnyEntity().onEnded { _ in
        enlarge.toggle()
    })
    .toolbar {
        ToolbarItemGroup(placement: .bottomOrnament) {
            VStack(spacing: 12) {
                Button {
                    enlarge.toggle()
                } label: {
                    Text(enlarge ? "Reduce RealityView Content" : "Enlarge RealityView Content")
                }
                .animation(.none, value: 0)
                .fontWeight(.semibold)
                
                Button {
                    appModel.showImmersiveSpace.toggle()
                } label: {
                    Text(appModel.showImmersiveSpace ? "Hide Immersive Space" : "Show Immersive Space")
                }
                .animation(.none, value: 0)
                .fontWeight(.semibold)
            }
        }
    }
}

}

#Preview(windowStyle: .volumetric) { ContentView() .environment(AppModel()) }

url: https://developer.apple.com/documentation/realitykit/composing-interactive-3d-content-with-realitykit-and-reality-composer-pro title: Composing interactive 3D content with RealityKit and Reality Composer Pro description: Build an interactive scene using an animation timeline. code_title: ImmersiveView.swift code_sample: import SwiftUI import RealityKit import RealityKitContent

// This view handles notifications from tap gestures and determines if the // tapped entity is an unhealthy hero plant. If the entity is an unhealthy // hero plant, and if the hero robot is available to help, then this view sends // the robot to the unhealthy plant.

【2†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

code_title: AppModel.swift code_sample: import SwiftUI

/// Maintains the app-wide state. @Observable public class AppModel { public var showImmersiveSpace = false public var immersiveSpaceIsShown = false }

url: https://developer.apple.com/documentation/realitykit/presenting-an-artists-scene title: Presenting an artist’s scene description: Display a scene from Reality Composer Pro in visionOS. code_title: ArtistWorkflowExampleApp.swift code_sample: import SwiftUI

@main struct ArtistWorkflowExampleApp: App {

@State private var appModel = AppModel()

@Environment(\.dismissImmersiveSpace) var dismissImmersiveSpace
@Environment(\.openImmersiveSpace) private var openImmersiveSpace

var body: some Scene {
    WindowGroup {
        ContentView()
            .environment(appModel)
            .onChange(of: appModel.showImmersiveSpace) { _, newValue in
                Task { @MainActor in
                    if newValue {
                        switch await openImmersiveSpace(id: "ImmersiveSpace") {
                        case .opened:
                            appModel.immersiveSpaceIsShown = true
                        case .error, .userCancelled:
                            fallthrough
                        @unknown default:
                            appModel.immersiveSpaceIsShown = false
                            appModel.showImmersiveSpace = false
                        }
                    } else if appModel.immersiveSpaceIsShown {
                        await dismissImmersiveSpace()
                    }
                }
            }
    }.windowStyle(.plain)
    .windowResizability(.contentSize)
    .defaultSize(width: 600, height: 300)

    ImmersiveSpace(id: "ImmersiveSpace") {
        ImmersiveView()
            .environment(appModel)
    }.immersionStyle(selection: .constant(.full), in: .full)
}

}

url: https://developer.apple.com/documentation/realitykit/presenting-an-artists-scene title: Presenting an artist’s scene description: Display a scene from Reality Composer Pro in visionOS. code_title: ContentView.swift code_sample: import SwiftUI import RealityKit import RealityKitContent

extension Image { init(resource name: String, ofType type: String) { guard let path = Bundle.main.path(forResource: name, ofType: type), let image = UIImage(contentsOfFile: path) else { self.init(name) return } self.init(uiImage: image) } }

struct ContentView: View { @Environment(.scenePhase) private var scenePhase @Environment(.dismissImmersiveSpace) var dismissImmersiveSpace @Environment(AppModel.self) var appModel

var body: some View {
    VStack(alignment: .trailing) {
        if appModel.immersiveSpaceIsShown {
            EmptyView()
        } else {
            Image(resource: "environment", ofType: "png")
            .resizable()
            .aspectRatio(contentMode: .fit)
            .glassBackgroundEffect()
        }
    }
    .onChange(of: scenePhase) { _, newPhase in
        Task { @MainActor in
            if newPhase == .background {
                appModel.showImmersiveSpace = false
            }
        }
    }
    .toolbar {
        ToolbarItemGroup(placement: .bottomOrnament) {
            VStack(spacing: 12) {

                Button {
                    appModel.showImmersiveSpace.toggle()
                } label: {
                    Text(appModel.showImmersiveSpace ?

【3†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

code_title: ImmersiveView.swift code_sample: import SwiftUI import RealityKit import RealityKitContent

struct ImmersiveView: View {

@Environment(AppModel.self) var appModel
@Environment(\.scenePhase) private var scenePhase

var body: some View {
    RealityView { content in
        // Add the initial RealityKit content.
        if let immersiveContentEntity = try? await Entity(named: "ArtistWorkflowExample", in: realityKitContentBundle) {
            content.add(immersiveContentEntity)

        }
    }
    .onChange(of: scenePhase) { _, newPhase in
        Task { @MainActor in
            if newPhase == .background {
                appModel.immersiveSpaceIsShown = false
                appModel.showImmersiveSpace = false
            }
        }
    }
}

}

#Preview(immersionStyle: .full) { ImmersiveView() .environment(AppModel()) }

url: https://developer.apple.com/documentation/realitykit/presenting-an-artists-scene title: Presenting an artist’s scene description: Display a scene from Reality Composer Pro in visionOS. code_title: Package.swift code_sample: // swift-tools-version:5.9 /* See the LICENSE.txt file for this sample’s licensing information.

Abstract: A package that contains model assets. */

import PackageDescription

let package = Package( name: "RealityKitContent", products: [ // Products define the executables and libraries a package produces, and make them visible to other packages. .library( name: "RealityKitContent", targets: ["RealityKitContent"]) ], 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: "RealityKitContent", dependencies: []) ] )

url: https://developer.apple.com/documentation/realitykit/presenting-an-artists-scene title: Presenting an artist’s scene description: Display a scene from Reality Composer Pro in visionOS. code_title: RealityKitContent.swift code_sample: import Foundation

/// The bundle for the RealityKitContent project. public let realityKitContentBundle = Bundle.module

url: https://developer.apple.com/documentation/realitykit/creating-a-spatial-drawing-app-with-realitykit title: Creating a spatial drawing app with RealityKit description: Use low-level mesh and texture APIs to achieve fast updates to a person’s brush strokes by integrating RealityKit with ARKit and SwiftUI. code_title: RealityKitDrawingApp.swift code_sample: import SwiftUI

@main struct RealityKitDrawingApp: App { private static let paletteWindowId: String = "Palette" private static let configureCanvasWindowId: String = "ConfigureCanvas" private static let splashScreenWindowId: String = "SplashScreen" private static let immersiveSpaceWindowId: String = "ImmersiveSpace"

/// The mode of the app determines which windows and immersive spaces should be open.
enum Mode: Equatable {
    case splashScreen
    case chooseWorkVolume
    case drawing
    
    var needsImmersiveSpace: Bool {
        return self != .splashScreen
    }
    
    var needsSpatialTracking: Bool {
        return self != .splashScreen
    }
    
    fileprivate var windowId: String {
        switch self {
        case .splashScreen: return splashScreenWindowId
        case .

【4†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

drawing: return paletteWindowId } } }

@State private var mode: Mode = .splashScreen
@State private var canvas = DrawingCanvasSettings()
@State private var brushState = BrushState()

@State private var immersiveSpacePresented: Bool = false
@State private var immersionStyle: ImmersionStyle = .mixed

@Environment(\.openWindow) private var openWindow
@Environment(\.dismissWindow) private var dismissWindow

@Environment(\.openImmersiveSpace) private var openImmersiveSpace
@Environment(\.dismissImmersiveSpace) private var dismissImmersiveSpace

@MainActor private func setMode(_ newMode: Mode) async {
    let oldMode = mode
    guard newMode != oldMode else { return }
    mode = newMode
    
    if !immersiveSpacePresented && newMode.needsImmersiveSpace {
        immersiveSpacePresented = true
        await openImmersiveSpace(id: Self.immersiveSpaceWindowId)
    } else if immersiveSpacePresented && !newMode.needsImmersiveSpace {
        immersiveSpacePresented = false
        await dismissImmersiveSpace()
    }
    
    openWindow(id: newMode.windowId)
    dismissWindow(id: oldMode.windowId)
}

var body: some Scene {
    Group {
        WindowGroup(id: Self.splashScreenWindowId) {
            SplashScreenView()
                .environment(\.setMode, setMode)
                .frame(width: 1000, height: 700)
                .fixedSize()
        }
        .windowResizability(.contentSize)
        .windowStyle(.plain)
        
        WindowGroup(id: Self.configureCanvasWindowId) {
            DrawingCanvasConfigurationView(settings: canvas)
                .environment(\.setMode, setMode)
                .frame(width: 300, height: 300)
                .fixedSize()
        }
        .windowResizability(.contentSize)
        
        WindowGroup(id: Self.paletteWindowId) {
            PaletteView(brushState: $brushState)
                .frame(width: 400, height: 550, alignment: .top)
                .fixedSize(horizontal: true, vertical: false)
        }
        .windowResizability(.contentSize)

        ImmersiveSpace(id: Self.immersiveSpaceWindowId) {
            ZStack {
                if mode == .chooseWorkVolume || mode == .drawing {
                    DrawingCanvasVisualizationView(settings: canvas)
                }
                
                if mode == .chooseWorkVolume {
                    DrawingCanvasPlacementView(settings: canvas)
                } else if mode == .drawing {
                    DrawingMeshView(canvas: canvas, brushState: $brushState)
                }
            }
            .frame(width: 0, height: 0).frame(depth: 0)
        }
        .immersionStyle(selection: $immersionStyle, in: .mixed)
    }
}

}

struct SetModeKey: EnvironmentKey { typealias Value = (RealityKitDrawingApp.Mode) async -> Void static let defaultValue: Value = { _ in } }

extension EnvironmentValues { var setMode: SetModeKey.Value { get { self[SetModeKey.self] } set { self[SetModeKey.self] = newValue } } }

url: https://developer.apple.com/documentation/realitykit/creating-a-spatial-drawing-app-with-realitykit title: Creating a spatial drawing app with RealityKit description: Use low-level mesh and texture APIs to achieve fast updates to a person’s brush strokes by integrating RealityKit with ARKit and SwiftUI.

【5†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

code_title: HappyBeamApp.swift code_sample: import SwiftUI import RealityKit

/// The structure of the Happy Beam app: a main window and a Full Space for gameplay. @main struct HappyBeamApp: App { @State private var gameModel = GameModel() @State private var immersionState: ImmersionStyle = .mixed

var body: some SwiftUI.Scene {
    WindowGroup("HappyBeam", id: "happyBeamApp") {
        HappyBeam()
            .environment(gameModel)
            .onAppear {
                guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene else {
                    return
                }
                    
                windowScene.requestGeometryUpdate(.Vision(resizingRestrictions: UIWindowScene.ResizingRestrictions.none))
            }
    }
    .windowStyle(.plain)
    
    ImmersiveSpace(id: "happyBeam") {
        HappyBeamSpace(gestureModel: HeartGestureModelContainer.heartGestureModel)
            .environment(gameModel)
    }
    .immersionStyle(selection: $immersionState, in: .mixed)
}

}

@MainActor enum HeartGestureModelContainer { private(set) static var heartGestureModel = HeartGestureModel() }

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: HappyBeamSpace.swift code_sample: import Accelerate import AVKit import Combine import GameController import RealityKit import SwiftUI import HappyBeamAssets

/// The Full Space that displays when someone plays the game. struct HappyBeamSpace: View { @ObservedObject var gestureModel: HeartGestureModel @Environment(GameModel.self) var gameModel

@State private var emittingBeam = false
@State private var blasterPosition = Float(0)
@State private var lastGestureUpdateTime: TimeInterval = 0
@State private var draggedEntity: Entity? = nil
@State private var positions: [SIMD3<Float>] = []
@State private var orientations: [simd_quatf] = []
@State private var collisionSubscription: EventSubscription?
@State private var activationSubscription: EventSubscription?

var collisionEntity = Entity()

var body: some View {
    RealityView { content in
        // The root entity.

【6†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

code_title: SpaceshipApp.swift code_sample: import SwiftUI import RealityKit

@main struct SpaceshipApp: App {

@State var appModel = AppModel()

#if os(visionOS) @Environment(.openWindow) var openWindow @Environment(.dismissWindow) var dismissWindow @Environment(.openImmersiveSpace) var openImmersiveSpace @Environment(.dismissImmersiveSpace) var dismissImmersiveSpace

var body: some SwiftUI.Scene {
    Group {
        WindowGroup {
            MenuView(appModel: appModel)
                .fixedSize()
        }
        .windowResizability(.contentSize)

        WindowGroup(id: "Hangar") {
            HangarView()
                .onDisappear {
                    appModel.isPresentingHangar = false
                }
                .fixedSize()
        }
        .windowStyle(.volumetric)

        WindowGroup(id: "AudioMixer") {
            AudioMixerView(mixer: appModel.audioMixer)
                .onDisappear {
                    appModel.isPresentingAudioMixer = false
                }
                .frame(width: 400)
        }
        .windowResizability(.contentSize)

#if targetEnvironment(simulator) WindowGroup(id: "ShipControl") { SimulatorShipControlView(controlParameters: appModel.shipControlParameters) } .windowResizability(.contentSize) #endif

        ImmersiveSpace(id: "FlightSchool") {
            FlightSchoolView()
        }
        .immersionStyle(selection: .constant(.mixed), in: .mixed)

        ImmersiveSpace(id: "ImmersiveSpace") {
            ImmersiveView()
                .environment(appModel)
        }
        .immersionStyle(selection: $appModel.immersionStyle, in: .mixed, .progressive)
    }
    .onChange(of: appModel.wantsToPresentImmersiveSpace) {
        appModel.isPresentingImmersiveSpace = true
    }
    .onChange(of: appModel.isPresentingImmersiveSpace) {
        Task {
            if appModel.isPresentingImmersiveSpace {
                switch await openImmersiveSpace(id: "ImmersiveSpace") {
                case .opened:
                    appModel.isPresentingImmersiveSpace = true
                case .error, .userCancelled:
                    fallthrough
                @unknown default:
                    appModel.isPresentingImmersiveSpace = false
                }

#if targetEnvironment(simulator) openWindow(id: "ShipControl") #endif } else { await dismissImmersiveSpace()

#if targetEnvironment(simulator) dismissWindow(id: "ShipControl") #endif } } } .onChange(of: appModel.isPresentingHangar) { if appModel.isPresentingHangar { openWindow(id: "Hangar") } else { dismissWindow(id: "Hangar") } } .onChange(of: appModel.isPresentingFlightSchool) { Task { if appModel.isPresentingFlightSchool { await openImmersiveSpace(id: "FlightSchool") } else { await dismissImmersiveSpace() } } } } #endif

#if os(iOS)

@State var isMenuExpanded: Bool = true

var body: some SwiftUI.Scene {
    Group {
        WindowGroup {
            ZStack {
                if appModel.isPresentingImmersiveSpace {
                    ZStack {
                        ImmersiveView()
                            .environment(appModel)

                        MultiTouchControlView(controlParameters: appModel.shipControlParameters)
                    }
                }

                if appModel.

【7†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

Error=(error).") } } .onChange(of: appModel.gamePhase, initial: true) { old, new in Task { appModel.isTransitioningBetweenGamePhases = true try await viewModel.transitionGamePhase(from: old, to: new) appModel.isTransitioningBetweenGamePhases = false

            viewModel.spaceship?.components.set(
                ShipControlComponent(parameters: appModel.shipControlParameters)
            )
        }
    }
    .onChange(of: appModel.wantsToPresentImmersiveSpace) {
        if appModel.wantsToPresentImmersiveSpace {
            appModel.isPresentingImmersiveSpace = true
        } else {
            Task {
                viewModel.fadeOutWorkMusic(duration: 2)
                viewModel.fadeOutJoyRideMusic(duration: 2)
                viewModel.planetsAudio.fadeOut()
                try await viewModel.fadeOutSpaceship()
                appModel.isPresentingImmersiveSpace = false
            }
        }
    }

#if os(visionOS) .onChange(of: appModel.surroundings, initial: true) { old, new in Task { appModel.updateImmersion() appModel.isTransitioningBetweenSurroundings = true try await viewModel.transitionSurroundings(from: old, to: new) appModel.isTransitioningBetweenSurroundings = false } } #endif } }

url: https://developer.apple.com/documentation/realitykit/creating-a-spaceship-game title: Creating a Spaceship game description: Build an immersive game using RealityKit audio, simulation, and rendering features. code_title: MenuView.swift code_sample: import SwiftUI import RealityKit

struct MenuView: View {

@Environment(\.openWindow) var openWindow
@Environment(\.dismissWindow) var dismissWindow

@Bindable var appModel: AppModel

var body: some View {
    VStack {
        if appModel.isPresentingImmersiveSpace {
            Toggle("Audio Mixer", systemImage: "slider.vertical.3", isOn: $appModel.isPresentingAudioMixer)
                .toggleStyle(.button)
                .onChange(of: appModel.isPresentingAudioMixer) {
                    if appModel.isPresentingAudioMixer {
                        openWindow(id: "AudioMixer")
                    } else {
                        dismissWindow(id: "AudioMixer")
                    }
                }
        } else {
            HStack {
                Toggle("Hangar", isOn: $appModel.isPresentingHangar)
                    .disabled(appModel.isPresentingFlightSchool || appModel.isPresentingImmersiveSpace)

#if os(visionOS) && !targetEnvironment(simulator) Toggle("Flight School", isOn: $appModel.isPresentingFlightSchool) .disabled(appModel.isPresentingImmersiveSpace || appModel.isPresentingHangar) #endif } .controlSize(.large) .toggleStyle(.button) }

        Divider()

        VStack {
            Picker("Game Phase", selection: $appModel.gamePhase) {
                ForEach(GamePhase.allCases, id: \.self) { phase in
                    Text(phase.displayName)
                }
            }
            .disabled(appModel.isTransitioningBetweenGamePhases)
            .pickerStyle(.segmented)

            Text(appModel.gamePhase == .joyRide ?

【8†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

code_title: ContentView.swift code_sample: import SwiftUI import RealityKit

/// The interface of the app. /// /// This view opens the immersive space and starts room tracking. struct ContentView: View { @Environment(.scenePhase) private var scenePhase

@Environment(\.openImmersiveSpace) var openImmersiveSpace
@Environment(\.dismissImmersiveSpace) var dismissImmersiveSpace

@Environment(AppState.self) var appState

@State private var visualization = "None"
var modes = ["None", "Occlusion", "Wall"]

var body: some View {
    Group {
        if appState.errorState != .noError {
            errorView
        } else if appState.isImmersive {
            viewWhileImmersed
        } else {
            viewWhileNonImmersed
        }
    }
    .padding()
    .frame(width: 600)
    .onChange(of: scenePhase) {
        if scenePhase != .active && appState.isImmersive {
            Task {
                await dismissImmersiveSpace()
                appState.isImmersive = false
                appState.showPreviewSphere = false
            }
        }
    }
    .onChange(of: appState.errorState) {
        if appState.errorState != .noError && appState.isImmersive {
            Task {
                await dismissImmersiveSpace()
                appState.isImmersive = false
                appState.showPreviewSphere = false
            }
        }
    }
}

@MainActor var viewWhileNonImmersed: some View {
    VStack {
        Spacer()
        Text("Enter the immersive space to start room tracking.")
        Spacer()
        Button("Enter immersive space") {
            Task {
                await openImmersiveSpace(id: immersiveSpace)
                appState.isImmersive = true
            }
        }
    }
}

@MainActor var viewWhileImmersed: some View {
    VStack(spacing: 25) {
        Spacer()
        Text("Place spheres in your environment, and observe their colors change when you move between rooms.")
        HStack {
            Button("Add a sphere", systemImage: "circle", action: {
                appState.showPreviewSphere = true
            })
            
            Button("Remove all spheres", systemImage: "xmark.bin", action: {
                Task {
                    await appState.removeAllWorldAnchors()
                }
            })
        }
        visualizationPicker
        Button(appState.isWallSelectionLocked ? "Unlock the wall" : "Lock the wall") {
            if appState.readyToLockWall {
                appState.isWallSelectionLocked.toggle()
            } else {
                logger.info("Not ready to lock a wall.")
            }
        }.disabled(visualization != "Wall")

        Spacer()
        Button("Leave immersive space") {
            Task {
                await dismissImmersiveSpace()
                appState.isImmersive = false
            }
        }
    }
}

@MainActor var errorView: some View {
    var message: String
    switch appState.errorState {
    case .noError: message = "" // Empty string, since the app only shows this view in case of an error.
    case .providerNotAuthorized: message = "The app hasn't authorized one or more data providers."
    case .providerNotSupported: message = "This device doesn't support one or more data providers."
    case .sessionError(let error): message = "Running the ARKitSession failed with an error: \(error)."

【9†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

public func exitExploration() { if let bodies = RobotProvider.shared.robotParts[.body] { for body in bodies { body.stopAllAnimations() } }

    robot?.animationState = .idle
    robot?.head.removeFromParent()
    robot?.body.removeFromParent()
    robot?.backpack.removeFromParent()
    
    robot?.head.transform.translation = .zero
    robot?.head.transform.rotation = simd_quatf()
    robot?.body.transform.translation = .zero
    robot?.body.transform.rotation = simd_quatf()
    robot?.backpack.transform.translation = .zero
    robot?.backpack.transform.rotation = simd_quatf()
   
    if let skeleton = robot?.body.findEntity(named: "rig_grp") {
        skeleton.jointPinComponent = nil
    }
    
    let children = explorationRoot.children
    for child in children {
        child.removeFromParent()
    }
    
    explorationEnvironment = nil

    restoreRobotInCreator()
    phase = .playing
}

}

url: https://developer.apple.com/documentation/visionos/bot-anist title: BOT-anist description: Build a multiplatform app that uses windows, volumes, and animations to create a robot botanist’s greenhouse. code_title: AppState.swift code_sample: import Foundation import RealityKit import BOTanistAssets import SwiftUI import Spatial

/// An enumeration that tracks the current phase of the app. public enum AppPhase: CaseIterable, Codable, Identifiable, Sendable { case waitingToStart // Waiting to start the game case loadingAssets // Loading assets from the Reality Composer Pro project case playing // Creating the robot. case exploration // Exploring the volume.

public var id: Self { self }

}

/// An object that maintains app-wide state. @Observable @MainActor public class AppState {

/// The root entity for the reality view in which robot creation happens.
var creationRoot = Entity()
/// The root entity for the exploration `RealityView`.
var explorationRoot = Entity()

/// The parent entity for the exploration environment.
var explorationEnvironment: Entity? = nil

var selectedBodyIndex: Int = 1
    
var robotData: RobotData!

/// A Boolean value that indicates whether the robot is celebrating after propagating every plant.
var celebrating: Bool = false

let materialColorParameterName = "mat_switch"
let materialLightsParameterName = "light_switch"
let materialFaceParameterName = "face_switch"

/// The finished and built robot. Intialized after creation phase.
var robot: RobotCharacter? = nil

/// The current phase of the app.
var phase = AppPhase.waitingToStart

/// The orientation of the robot model in the creation screen.
var robotCreationOrientation: Rotation3D = Rotation3D()

var isRotating = false

/// The camera establishing the rendering perspective for the creation screen `RealityView` for platforms other than visionOS.
let robotCamera = PerspectiveCamera()
/// The camera establishing the rendering perspective for the exploration screen `RealityView` for platforms other than visionOS.

【10†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

/// /// The app uses this value for representing the canvas visually. var floorHeight: Float = 0

/// Returns a Boolean value that tells you if a point is considered inside of the drawing canvas.
func isInsideCanvas(_ point: SIMD3<Float>) -> Bool {
    let localPos = point - placementPosition
    let localPos2 = SIMD2<Float>(localPos.x, localPos.z)
    return length(localPos2) < radius
}

}

url: https://developer.apple.com/documentation/realitykit/creating-a-spatial-drawing-app-with-realitykit title: Creating a spatial drawing app with RealityKit description: Use low-level mesh and texture APIs to achieve fast updates to a person’s brush strokes by integrating RealityKit with ARKit and SwiftUI. code_title: DrawingCanvasConfigurationView.swift code_sample: import SwiftUI import RealityKit

/// A view that contains configurations for the size of a drawing canvas. /// /// This view should be used in a window. /// /// It allows a person to configure the size of their drawing canvas, and also has a "Reset Placement" /// button that brings the selected canvas location back to the location of the window. struct DrawingCanvasConfigurationView: View { @Bindable var settings: DrawingCanvasSettings

@MainActor @State var placementResetPose: Entity?

@Environment(\.setMode) var setMode
@Environment(\.physicalMetrics) var physicalMetrics

private let resetPose = Entity()

/// Resets the position of the placement entity.
///
/// The ``DrawingCanvasSettings/placementEntity`` should be in the immersive space,
/// to be coincident with ``placementResetPose``, which is positioned relative to the window.
///
/// - Parameters:
///   - duration: The time in seconds of the animation takes to move `placementEntity`.
private func resetPlacement(duration: TimeInterval = 0.2) {
    if let resetPoseMatrix = placementResetPose?.transformMatrix(relativeTo: .immersiveSpace) {
        var transform = Transform(matrix: resetPoseMatrix)
        transform.scale = .one
        settings.placementEntity.move(to: transform, relativeTo: nil, duration: duration)
        settings.placementEntity.isEnabled = true
    }
}

/// A Boolean value that determines whether the canvas placement handle is locked to the location of this view.
///
/// If `true`, the canvas placement handle is locked.
private var isPlacementLockedToWindow: Bool {
    if !settings.placementEntity.isEnabled {
        return true
    } else if let component = settings.placementEntity.components[DrawingCanvasPlacementComponent.self] {
        return component.lockedToWindow
    }
    return false
}

var body: some View {
    VStack {
        Spacer(minLength: 20)

        Text("Set up your canvas").font(.system(.title))

        Spacer(minLength: 10)

        // This `RealityView` contains no visible entities.
        // Its purpose is to hold `placementRestPose`, so that
        // when a person taps "Reset Placement" the app knows where to move `placementEntity` back to.
        RealityView { content in
            resetPose.position.x = 0.2
            content.add(resetPose)
            
            placementResetPose = resetPose
            settings.placementEntity.isEnabled = false
            
            resetPlacement()
        } update: { content in
            if isPlacementLockedToWindow {
                resetPlacement()
            }
        }
        .task {
            try?

【11†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

public func exitExploration() { if let bodies = RobotProvider.shared.robotParts[.body] { for body in bodies { body.stopAllAnimations() } }

    robot?.animationState = .idle
    robot?.head.removeFromParent()
    robot?.body.removeFromParent()
    robot?.backpack.removeFromParent()
    
    robot?.head.transform.translation = .zero
    robot?.head.transform.rotation = simd_quatf()
    robot?.body.transform.translation = .zero
    robot?.body.transform.rotation = simd_quatf()
    robot?.backpack.transform.translation = .zero
    robot?.backpack.transform.rotation = simd_quatf()
   
    if let skeleton = robot?.body.findEntity(named: "rig_grp") {
        skeleton.jointPinComponent = nil
    }
    
    let children = explorationRoot.children
    for child in children {
        child.removeFromParent()
    }
    
    explorationEnvironment = nil

    restoreRobotInCreator()
    phase = .playing
}

}

url: https://developer.apple.com/documentation/visionOS/BOT-anist title: BOT-anist description: Build a multiplatform app that uses windows, volumes, and animations to create a robot botanist’s greenhouse. code_title: AppState.swift code_sample: import Foundation import RealityKit import BOTanistAssets import SwiftUI import Spatial

/// An enumeration that tracks the current phase of the app. public enum AppPhase: CaseIterable, Codable, Identifiable, Sendable { case waitingToStart // Waiting to start the game case loadingAssets // Loading assets from the Reality Composer Pro project case playing // Creating the robot. case exploration // Exploring the volume.

public var id: Self { self }

}

/// An object that maintains app-wide state. @Observable @MainActor public class AppState {

/// The root entity for the reality view in which robot creation happens.
var creationRoot = Entity()
/// The root entity for the exploration `RealityView`.
var explorationRoot = Entity()

/// The parent entity for the exploration environment.
var explorationEnvironment: Entity? = nil

var selectedBodyIndex: Int = 1
    
var robotData: RobotData!

/// A Boolean value that indicates whether the robot is celebrating after propagating every plant.
var celebrating: Bool = false

let materialColorParameterName = "mat_switch"
let materialLightsParameterName = "light_switch"
let materialFaceParameterName = "face_switch"

/// The finished and built robot. Intialized after creation phase.
var robot: RobotCharacter? = nil

/// The current phase of the app.
var phase = AppPhase.waitingToStart

/// The orientation of the robot model in the creation screen.
var robotCreationOrientation: Rotation3D = Rotation3D()

var isRotating = false

/// The camera establishing the rendering perspective for the creation screen `RealityView` for platforms other than visionOS.
let robotCamera = PerspectiveCamera()
/// The camera establishing the rendering perspective for the exploration screen `RealityView` for platforms other than visionOS.

【12†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

"Reduce RealityView Content" : "Enlarge RealityView Content") } .animation(.none, value: 0) .fontWeight(.semibold)

                Button {
                    appModel.showImmersiveSpace.toggle()
                } label: {
                    Text(appModel.showImmersiveSpace ? "Hide Immersive Space" : "Show Immersive Space")
                }
                .animation(.none, value: 0)
                .fontWeight(.semibold)
            }
        }
    }
}

}

#Preview(windowStyle: .volumetric) { ContentView() .environment(AppModel()) }

url: https://developer.apple.com/documentation/realitykit/composing-interactive-3d-content-with-realitykit-and-reality-composer-pro title: Composing interactive 3D content with RealityKit and Reality Composer Pro description: Build an interactive scene using an animation timeline. code_title: ImmersiveView.swift code_sample: import SwiftUI import RealityKit import RealityKitContent

// This view handles notifications from tap gestures and determines if the // tapped entity is an unhealthy hero plant. If the entity is an unhealthy // hero plant, and if the hero robot is available to help, then this view sends // the robot to the unhealthy plant. struct ImmersiveView: View {

@Environment(AppModel.self) var appModel
@Environment(\.scenePhase) private var scenePhase

private let reachToPoppyReceived = NotificationCenter.default.publisher(for: .reachToPoppyNotification)
private let reachToCoffeeBerryReceived = NotificationCenter.default.publisher(for: .reachToCoffeeBerryNotification)
private let reachToYuccaReceived = NotificationCenter.default.publisher(for: .reachToYuccaNotification)
private let startWateringReceived = NotificationCenter.default.publisher(for: .startWateringNotification)
private let stopWateringReceived = NotificationCenter.default.publisher(for: .stopWateringNotification)
private let returnHomeReceived = NotificationCenter.default.publisher(for: .returnHomeNotification)

var body: some View {
    RealityView { content in
        // Add the initial RealityKit content.
        if let immersiveContentEntity = try? await Entity(named: "Immersive", in: realityKitContentBundle) {
            content.add(immersiveContentEntity)
        }
    }
    .gesture(TapGesture().targetedToAnyEntity()
        .onEnded({ value in
            // Ensure the tapped entity is a hero plant and that it needs tending.
            if let scene = value.entity.scene,
               let heroRobot = getHeroRobotIfAvailable(scene: scene),
               isPlantUnhealthy(entity: value.entity),
               heroRobot.components[HeroRobotRuntimeComponent.self] != nil {
                heroRobot.components[HeroRobotRuntimeComponent.self]?.setState(newState: .moving)
                // Apply the tap behaviors on the entity.
                _ = value.entity.applyTapForBehaviors()
            }
        })
    )
    .onChange(of: scenePhase) { _, newPhase in
        Task { @MainActor in
            if newPhase == .background {
                appModel.immersiveSpaceIsShown = false
                appModel.showImmersiveSpace = false
            }
        }
    }
    .onReceive(reachToPoppyReceived) { (output) in
        guard let entity = output.userInfo?["RealityKit.NotifyAction.SourceEntity"] as? Entity,
              let heroRobot = getHeroRobot(from: entity.scene) else { return }

        (heroRobot.components[HeroRobotRuntimeComponent.self])?.setState(newState: .beginReach, targetPlantName: "hero_poppy")
    }
    .onReceive(reachToCoffeeBerryReceived) { (output) in
        guard let entity = output.userInfo?["RealityKit.NotifyAction.SourceEntity"] as?

【13†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

uniform: SolidBrushStyleView(settings: $brushState.uniformStyleSettings) .id("BrushStyleView") case .sparkle: SparkleBrushStyleView(settings: $brushState.sparkleStyleSettings) .id("BrushStyleView") } } .animation(.easeInOut, value: brushState.brushType) } } } }

url: https://developer.apple.com/documentation/realitykit/creating-a-spatial-drawing-app-with-realitykit title: Creating a spatial drawing app with RealityKit description: Use low-level mesh and texture APIs to achieve fast updates to a person’s brush strokes by integrating RealityKit with ARKit and SwiftUI. code_title: PaletteView.swift code_sample: import SwiftUI import RealityKit import RealityKitContent

struct PaletteView: View { @Binding var brushState: BrushState

@State var isDrawing: Bool = false
@State var isSettingsPopoverPresented: Bool = false

var body: some View {
    VStack {
        HStack {
            Text("Palette")
                .font(.title)
                .padding()
        }

        Divider()
            .padding(.horizontal, 20)

        BrushTypeView(brushState: $brushState)
            .padding(.horizontal, 20)

        Spacer()
        
        Divider()
            .padding(.horizontal, 20)

        PresetBrushSelectorView(brushState: $brushState)
            .frame(minHeight: 125)
    }
    .padding(.vertical, 20)
}

}

url: https://developer.apple.com/documentation/realitykit/creating-a-spatial-drawing-app-with-realitykit title: Creating a spatial drawing app with RealityKit description: Use low-level mesh and texture APIs to achieve fast updates to a person’s brush strokes by integrating RealityKit with ARKit and SwiftUI. code_title: PresetBrushStroke.swift code_sample: struct PresetBrushStroke { static let samples: [SIMD3] = { let points: [SIMD2] = [ [80, 273], [203, 152], [236, 125], [264, 106], [283, 100], [295, 104], [300, 107], [307, 115], [309, 128], [304, 144], [296, 158], [260, 206], [210, 264], [181, 303], [174, 325], [175, 344], [186, 355], [200, 358], [216, 352], [234, 340], [251, 326], [322, 263], [344, 251], [357, 250], [364, 254], [370, 263], [368, 275], [361, 290], [330, 347], [328, 365], [336, 372], [345, 374], [356, 369], [369, 359], [387, 344] ]

    let extents: SIMD2<Float> = [512, 512]
    let halfExtents = extents / 2
    
    let center: SIMD2<Float> = [256, 256]

    return points.map { point in
        var framedPoint = SIMD3<Float>((point - center) / halfExtents, 0)
        framedPoint.y *= -1
        return framedPoint
    }
}()

}

url: https://developer.apple.com/documentation/realitykit/creating-a-spatial-drawing-app-with-realitykit title: Creating a spatial drawing app with RealityKit description: Use low-level mesh and texture APIs to achieve fast updates to a person’s brush strokes by integrating RealityKit with ARKit and SwiftUI.

【14†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

.progressive) } .onChange(of: appModel.wantsToPresentImmersiveSpace) { appModel.isPresentingImmersiveSpace = true } .onChange(of: appModel.isPresentingImmersiveSpace) { Task { if appModel.isPresentingImmersiveSpace { switch await openImmersiveSpace(id: "ImmersiveSpace") { case .opened: appModel.isPresentingImmersiveSpace = true case .error, .userCancelled: fallthrough @unknown default: appModel.isPresentingImmersiveSpace = false }

#if targetEnvironment(simulator) openWindow(id: "ShipControl") #endif } else { await dismissImmersiveSpace()

#if targetEnvironment(simulator) dismissWindow(id: "ShipControl") #endif } } } .onChange(of: appModel.isPresentingHangar) { if appModel.isPresentingHangar { openWindow(id: "Hangar") } else { dismissWindow(id: "Hangar") } } .onChange(of: appModel.isPresentingFlightSchool) { Task { if appModel.isPresentingFlightSchool { await openImmersiveSpace(id: "FlightSchool") } else { await dismissImmersiveSpace() } } } } #endif

#if os(iOS)

@State var isMenuExpanded: Bool = true

var body: some SwiftUI.Scene {
    Group {
        WindowGroup {
            ZStack {
                if appModel.isPresentingImmersiveSpace {
                    ZStack {
                        ImmersiveView()
                            .environment(appModel)

                        MultiTouchControlView(controlParameters: appModel.shipControlParameters)
                    }
                }

                if appModel.isPresentingHangar {
                    HangarView()
                }

                if appModel.isPresentingAudioMixer {
                    AudioMixerView(mixer: appModel.audioMixer)
                        .frame(width: 200)
                        .padding(20)
                        .background(.thickMaterial, in: RoundedRectangle(cornerRadius: 20))
                        .anchorToTopRight()
                }

                DisclosureGroup("Menu", isExpanded: $isMenuExpanded) {
                    MenuView(appModel: appModel)
                }
                .frame(width: isMenuExpanded ? 300 : 80)
                .padding(.horizontal, 20)
                .padding(.vertical, 10)
                .background(.thickMaterial, in: RoundedRectangle(cornerRadius: 20))
                .anchorToTopLeft()
            }
            .ignoresSafeArea()
        }
        .onChange(of: appModel.wantsToPresentImmersiveSpace) {
            appModel.isPresentingImmersiveSpace = true
        }
    }
}

#endif }

url: https://developer.apple.com/documentation/realitykit/creating-a-spaceship-game title: Creating a Spaceship game description: Build an immersive game using RealityKit audio, simulation, and rendering features.

【15†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

MeshResource(from: newMesh) { if entity.components.has(ModelComponent.self) { entity.components[ModelComponent.self]!.mesh = resource } else { let modelComponent = ModelComponent(mesh: resource, materials: [brushComponent.material]) entity.components.set(modelComponent) } } } } }

url: https://developer.apple.com/documentation/realitykit/creating-a-spatial-drawing-app-with-realitykit title: Creating a spatial drawing app with RealityKit description: Use low-level mesh and texture APIs to achieve fast updates to a person’s brush strokes by integrating RealityKit with ARKit and SwiftUI. code_title: SolidBrushVertex+LowLevelMesh.swift code_sample: import RealityKit

extension SolidBrushVertex { static var vertexAttributes: [LowLevelMesh.Attribute] { typealias Attribute = LowLevelMesh.Attribute

    return [
        Attribute(semantic: .position, format: .float3, layoutIndex: 0,
                  offset: MemoryLayout.offset(of: \Self.position)!),

        Attribute(semantic: .normal, format: .float3, layoutIndex: 0,
                  offset: MemoryLayout.offset(of: \Self.normal)!),

        Attribute(semantic: .bitangent, format: .float3, layoutIndex: 0,
                  offset: MemoryLayout.offset(of: \Self.bitangent)!),

        Attribute(semantic: .color, format: .half3, layoutIndex: 0,
                  offset: MemoryLayout.offset(of: \Self.color)!),
        
        Attribute(semantic: .uv1, format: .float, layoutIndex: 0,
                  offset: MemoryLayout.offset(of: \Self.curveDistance)!),
        
        Attribute(semantic: .uv3, format: .float2, layoutIndex: 0,
                  offset: MemoryLayout.offset(of: \Self.materialProperties)!)
    ]
}

}

url: https://developer.apple.com/documentation/realitykit/creating-a-spatial-drawing-app-with-realitykit title: Creating a spatial drawing app with RealityKit description: Use low-level mesh and texture APIs to achieve fast updates to a person’s brush strokes by integrating RealityKit with ARKit and SwiftUI. code_title: SolidDrawingMeshGenerator.swift code_sample: import RealityKit

final class SolidDrawingMeshGenerator { /// The extruder this generator uses to generate the mesh geometry. private var extruder: CurveExtruderWithEndcaps

/// The entity which this generator populates with mesh data.
private let rootEntity: Entity

var samples: [CurveSample] { extruder.samples }
    
init(rootEntity: Entity, material: Material) {
    extruder = CurveExtruderWithEndcaps()
    self.rootEntity = rootEntity
    rootEntity.position = .zero
    rootEntity.components.set(SolidBrushComponent(generator: self, material: material))
}

@MainActor
func update() throws -> LowLevelMesh? {
    try extruder.update()
}

func removeLast(sampleCount: Int) {
    extruder.removeLast(sampleCount: sampleCount)
}

func pushSamples(curve: [CurveSample]) {
    extruder.append(samples: curve)
}

func beginNewStroke() {
    extruder.beginNewStroke()
}

}

url: https://developer.apple.com/documentation/realitykit/creating-a-spatial-drawing-app-with-realitykit title: Creating a spatial drawing app with RealityKit description: Use low-level mesh and texture APIs to achieve fast updates to a person’s brush strokes by integrating RealityKit with ARKit and SwiftUI. code_title: CurveSample.swift code_sample: import simd

/// An object that represents points that a smooth curve sampler emits.

【16†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

joyRideDescription : workDescription) .font(.caption) .foregroundStyle(.secondary) .multilineTextAlignment(.leading) .frame(maxWidth: .infinity, alignment: .leading) .padding([.bottom, .horizontal], 8) }

        Divider()

#if os(visionOS) SurroundingsPicker(selection: $appModel.surroundings) .disabled(appModel.isTransitioningBetweenSurroundings)

        Divider()

#endif

        Toggle(
            appModel.wantsToPresentImmersiveSpace ? "Return" : "Fly",
            isOn: $appModel.wantsToPresentImmersiveSpace
        )
        .font(.largeTitle)
        .toggleStyle(FlyReturnToggleStyle())
        .buttonBorderShape(.roundedRectangle(radius: 36))
        .disabled(flyReturnToggleIsDisabled)
    }
    .padding(.vertical, 10)
    .frame(width: 300)
}

var flyReturnToggleIsDisabled: Bool {
    appModel.isPresentingHangar ||
    appModel.isPresentingFlightSchool ||
    appModel.isTransitioningBetweenSurroundings ||
    appModel.isTransitioningBetweenGamePhases ||
    (!appModel.wantsToPresentImmersiveSpace && appModel.isPresentingImmersiveSpace)
}

var joyRideDescription: String {
    """
    Simply bask in the sensation of flight.

    No matter how hard you fly into things, you don't have to worry about the spaceship \
    exploding!
    """
}

var workDescription: String {
    """
    Deliver cargo from planet to planet.

    Watch out: If you run into too many things hard enough, the spaceship will explode!
    """
}

}

struct FlyReturnToggleStyle: ToggleStyle { func makeBody(configuration: Configuration) -> some View { Button { configuration.isOn.toggle() } label: { configuration.label .frame(maxWidth: .infinity, idealHeight: 100) } } }

url: https://developer.apple.com/documentation/realitykit/creating-a-spaceship-game title: Creating a Spaceship game description: Build an immersive game using RealityKit audio, simulation, and rendering features. code_title: RealityView+WorldTracking.swift code_sample: import SwiftUI import RealityKit

#if os(iOS)

extension RealityKit.RealityViewCameraContent { func setupWorldTracking() async { let configuration = SpatialTrackingSession.Configuration( tracking: [.plane], sceneUnderstanding: [.shadow], camera: .back ) let session = SpatialTrackingSession() _ = await session.run(configuration) } }

#endif

url: https://developer.apple.com/documentation/realitykit/creating-a-spaceship-game title: Creating a Spaceship game description: Build an immersive game using RealityKit audio, simulation, and rendering features.

【17†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

} } }

/// Creates a world anchor with the input transform and adds the anchor to the world tracking provider.
func addWorldAnchor(at transform: simd_float4x4) async {
    
    let worldAnchor = WorldAnchor(originFromAnchorTransform: transform)
    do {
        try await self.worldTracking.addAnchor(worldAnchor)
    } catch {
        // Adding world anchors can fail, for example when you reach the limit
        // for total world anchors per app.
        logger.error("Failed to add world anchor \(worldAnchor.id) with error: \(error).")
    }
}

}

url: https://developer.apple.com/documentation/arkit/arkit_in_visionos/building_local_experiences_with_room_tracking title: Building local experiences with room tracking description: Use room tracking in visionOS to provide custom interactions with physical spaces. code_title: ARKitRoomTrackingApp.swift code_sample: import OSLog import SwiftUI

let immersiveSpace = "ImmersiveSpace"

/// The entry point for the app. @main @MainActor struct ARKitRoomTrackingApp: App {

@State private var appState = AppState()

var body: some Scene {
    WindowGroup {
        ContentView()
            .environment(appState)
    }.defaultSize(CGSize(width: 800, height: 400))
    
    ImmersiveSpace(id: immersiveSpace) {
        WorldAndRoomView()
            .environment(appState)
    }
}

}

@MainActor let logger = Logger(subsystem: "com.example.apple-samplecode.arkitroomtracking.ARKitRoomTracking", category: "general")

url: https://developer.apple.com/documentation/arkit/arkit_in_visionos/building_local_experiences_with_room_tracking title: Building local experiences with room tracking description: Use room tracking in visionOS to provide custom interactions with physical spaces. code_title: ContentView.swift code_sample: import SwiftUI import RealityKit

/// The interface of the app. /// /// This view opens the immersive space and starts room tracking. struct ContentView: View { @Environment(.scenePhase) private var scenePhase

@Environment(\.openImmersiveSpace) var openImmersiveSpace
@Environment(\.dismissImmersiveSpace) var dismissImmersiveSpace

@Environment(AppState.self) var appState

@State private var visualization = "None"
var modes = ["None", "Occlusion", "Wall"]

var body: some View {
    Group {
        if appState.errorState != .noError {
            errorView
        } else if appState.isImmersive {
            viewWhileImmersed
        } else {
            viewWhileNonImmersed
        }
    }
    .padding()
    .frame(width: 600)
    .onChange(of: scenePhase) {
        if scenePhase != .active && appState.isImmersive {
            Task {
                await dismissImmersiveSpace()
                appState.isImmersive = false
                appState.showPreviewSphere = false
            }
        }
    }
    .onChange(of: appState.errorState) {
        if appState.errorState != .noError && appState.isImmersive {
            Task {
                await dismissImmersiveSpace()
                appState.isImmersive = false
                appState.showPreviewSphere = false
            }
        }
    }
}

@MainActor var viewWhileNonImmersed: some View {
    VStack {
        Spacer()
        Text("Enter the immersive space to start room tracking.")

【18†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

code_title: TextureMapsView.swift code_sample: import SwiftUI import RealityKit

struct TextureMapsView: View { @Environment(AppDataModel.self) private var appDataModel: AppDataModel @State private var selectedTextureMap = PhotogrammetrySession.Configuration.CustomDetailSpecification().outputTextureMaps.rawValue

var body: some View {
    Picker("Texture Maps:", selection: $selectedTextureMap) {
        Text("Diffuse Color")
            .tag(PhotogrammetrySession.Configuration.CustomDetailSpecification.TextureMapOutputs.diffuseColor.rawValue)
        
        Text("Normal")
            .tag(PhotogrammetrySession.Configuration.CustomDetailSpecification.TextureMapOutputs.normal.rawValue)
        
        Text("Roughness")
            .tag(PhotogrammetrySession.Configuration.CustomDetailSpecification.TextureMapOutputs.roughness.rawValue)
        
        Text("Displacement")
            .tag(PhotogrammetrySession.Configuration.CustomDetailSpecification.TextureMapOutputs.displacement.rawValue)
        
        Text("Ambient Occlusion")
            .tag(PhotogrammetrySession.Configuration.CustomDetailSpecification.TextureMapOutputs.ambientOcclusion.rawValue)
        
        Text("All")
            .tag(PhotogrammetrySession.Configuration.CustomDetailSpecification.TextureMapOutputs.all.rawValue)
    }
    .onChange(of: selectedTextureMap, initial: false) {
        let newValue = PhotogrammetrySession.Configuration.CustomDetailSpecification.TextureMapOutputs(rawValue: selectedTextureMap)
        appDataModel.sessionConfiguration.customDetailSpecification.outputTextureMaps = newValue
        appDataModel.detailLevelOptionsUnderQualityMenu = .custom
    }
    .onAppear {
        selectedTextureMap = appDataModel.sessionConfiguration.customDetailSpecification.outputTextureMaps.rawValue
    }
}

}

url: https://developer.apple.com/documentation/realitykit/building-an-object-reconstruction-app title: Building an object reconstruction app description: Reconstruct objects from user-selected input images by using photogrammetry. code_title: TextureResolutionView.swift code_sample: import SwiftUI import RealityKit

struct TextureResolutionView: View { @Environment(AppDataModel.self) private var appDataModel: AppDataModel

var body: some View {
    @Bindable var appDataModel = appDataModel
    Picker("Texture Resolution:", selection: $appDataModel.sessionConfiguration.customDetailSpecification.maximumTextureDimension) {
        Text("1K")
            .tag(PhotogrammetrySession.Configuration.CustomDetailSpecification.TextureDimension.oneK)
        
        Text("2K")
            .tag(PhotogrammetrySession.Configuration.CustomDetailSpecification.TextureDimension.twoK)
        
        Text("4K")
            .tag(PhotogrammetrySession.Configuration.CustomDetailSpecification.TextureDimension.fourK)
        
        Text("8K")
            .tag(PhotogrammetrySession.Configuration.CustomDetailSpecification.TextureDimension.eightK)
        
        Text("16K")
            .tag(PhotogrammetrySession.Configuration.CustomDetailSpecification.TextureDimension.sixteenK)
    }
    .onChange(of: appDataModel.sessionConfiguration.customDetailSpecification.maximumTextureDimension, initial: false) {
        appDataModel.detailLevelOptionsUnderQualityMenu = .custom
    }
}

}

url: https://developer.apple.com/documentation/realitykit/building-an-object-reconstruction-app title: Building an object reconstruction app description: Reconstruct objects from user-selected input images by using photogrammetry. code_title: FolderOptionsView.swift code_sample: import SwiftUI import RealityKit

struct FolderOptionsView: View { @Environment(AppDataModel.self) private var appDataModel: AppDataModel

var body: some View {
    Section {
        ImageFolderView()
        
        ModelNameField()
        
        ModelFolderView()
    }
}

}

url: https://developer.apple.com/documentation/realitykit/building-an-object-reconstruction-app title: Building an object reconstruction app description: Reconstruct objects from user-selected input images by using photogrammetry.

【19†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

{ appState.rotateSelectedEntities(direction: .clockwise) } .accessibilityAction(named: Text("Rotate selected pieces 90 degrees counter-clockwise", comment: "Accessibility action: An action to rotate the selected pice.")) { appState.rotateSelectedEntities(direction: .counterClockwise) } .simultaneousGesture( TapGesture(count: 2) .targetedToAnyEntity() .onEnded({ value in guard appState.phase == .buildingTrack else { return } shouldSingleTap = false guard let entity = value.entity.connectableAncestor else { logger.error("Double tap entity not found.") return } if appState.trackPieceBeingEdited == nil { appState.trackPieceBeingEdited = entity } else { appState.toggleTrackPieceInSelection(entity: entity) } appState.updateSelection() }) ) .simultaneousGesture( TapGesture() .targetedToAnyEntity() .onEnded({ value in guard appState.phase == .buildingTrack else { return } Task { defer { appState.updateVisuals() }

                    shouldSingleTap = true
                    try? await Task.sleep(for: .seconds(doubleTapTolerance))
                    if shouldSingleTap {
                        guard let entity = value.entity.connectableAncestor else {
                            logger.error("Tap gesture provided no entity.")
                            return
                        }
                        guard entity != appState.placePieceMarker else {
                            logger.info("Tap on placement marker. This piece doesn't support edit mode.")
                            return
                        }

                        SoundEffectPlayer.shared.play(.selectPiece, from: entity)

                        if appState.trackPieceBeingEdited == entity {
                            appState.trackPieceBeingEdited = nil
                            appState.clearSelection()
                            entity.connectableStateComponent?.isSelected = false
                            
                            appState.hideEditAttachment()
                            appState.updateConnections()
                            appState.updateSelection()
                        } else {
                            Task {
                                appState.trackPieceBeingEdited = entity.connectableAncestor
                                appState.trackPieceBeingEdited?.connectableStateComponent?.isSelected = true
                                appState.clearSelection(keepPrimary: true)
                                appState.showEditAttachment()
                            }
                        }
                        appState.updateConnections()
                        appState.updateSelection()
                    }
                    shouldSingleTap = false
                }
            })
    )
    .onChange(of: appState.phase.isImmersed) { _, showMRView in
        if !showMRView {
            dismiss()
        }
    }
}

}

#Preview { TrackBuildingView() .environment(AppState()) }

url: https://developer.apple.com/documentation/visionos/incorporating-real-world-surroundings-in-an-immersive-experience title: Incorporating real-world surroundings in an immersive experience description: Create an immersive experience by making your app’s content respond to the local shape of the world. code_title: ContentView.swift code_sample: import SwiftUI import RealityKit

/// The initial interface of the app. /// /// It dismisses itself after the immersive space opens and scene reconstruction starts running. Visible: 0% - 100%To handle the exit functionality in a SwiftUI RealityKit app, it's essential to manage the transition of the app state properly when it goes into the background or when certain conditions are met that should trigger an exit from the immersive space. Here are some key steps and examples:

  1. Monitor Scene Phase Changes: Use the @Environment(\.scenePhase) property to detect when the app transitions to the background, and handle the necessary clean-up or state changes.

  2. Dismiss Immersive Space: Use the dismissImmersiveSpace environment variable to exit from the immersive space when required.

  3. Update App State: Manage a central state model (like AppModel or AppState) to reflect changes in the app's status, ensuring a seamless exit or state transition.

Here is an example implementation based on the provided documentation:

import SwiftUI
import RealityKit

struct ContentView: View {
    @Environment(\.scenePhase) private var scenePhase
    @Environment(\.dismissImmersiveSpace) var dismissImmersiveSpace
    @Environment(AppState.self) var appState

    var body: some View {
        VStack {
            if appState.isImmersive {
                immersiveView
            } else {
                nonImmersiveView
            }
        }
        .onChange(of: scenePhase) { newPhase in
            handleScenePhaseChange(newPhase)
        }
        .onChange(of: appState.errorState) { _ in
            handleAppStateChange()
        }
    }

    @MainActor private var immersiveView: some View {
        VStack {
            Text("Immersive Mode")
            Button("Exit Immersive Mode") {
                Task {
                    await dismissImmersiveSpace()
                    appState.isImmersive = false
                }
            }
        }
    }

    @MainActor private var nonImmersiveView: some View {
        VStack {
            Text("Non-Immersive Mode")
            Button("Enter Immersive Mode") {
                Task {
                    await openImmersiveSpace(id: "ImmersiveSpace")
                    appState.isImmersive = true
                }
            }
        }
    }

    private func handleScenePhaseChange(_ newPhase: ScenePhase) {
        if newPhase != .active && appState.isImmersive {
            Task {
                await dismissImmersiveSpace()
                appState.isImmersive = false
            }
        }
    }

    private func handleAppStateChange() {
        if appState.errorState != .noError && appState.isImmersive {
            Task {
                await dismissImmersiveSpace()
                appState.isImmersive = false
            }
        }
    }
}

class AppState: ObservableObject {
    @Published var isImmersive: Bool = false
    @Published var errorState: ErrorState = .noError

    enum ErrorState {
        case noError
        case someError
    }
}

In this example:

  • Scene Phase Handling: The handleScenePhaseChange method ensures the app exits immersive mode if it moves to the background.
  • State Management: The AppState class tracks whether the app is in immersive mode and manages error states.
  • Entering and Exiting Immersive Mode: Buttons in the UI allow users to enter or exit immersive mode manually, updating the AppState accordingly.

This approach ensures the app transitions smoothly between states and handles exits appropriately.

For additional details on creating and managing immersive experiences, refer to Apple's documentation on RealityKit and SwiftUI integration【11:0†source】【11:2†source】【11:4†source】.How can I "exit" an iOS / visionOS app?msearch(["exit iOS visionOS app"])# 【0†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】 let sphere = createPreviewSphere() // Places the preview one meter in front of the head. sphere.position = [0, 0, -1]

        // Creates a head anchor and attaches the preview sphere.
        let headAnchor = AnchorEntity(.head)
        content.add(headAnchor)
        headAnchor.addChild(sphere)
        
        previewSphere = sphere
        // Updates and renders the wall in front of the person at 10 Hz.
        updateFacingWallTask = run(appState.updateFacingWall, withFrequency: 10)
    }
    .onAppear {
        appState.isImmersive = true
    }
    .onDisappear {
        appState.isImmersive = false
        updateFacingWallTask?.cancel()
    }
    .task {
        await appState.runSession()
    }
    .task {
        await appState.monitorSessionUpdates()
    }
    .task {
        await appState.processRoomTrackingUpdates()
    }
    .task {
        await appState.processWorldTrackingUpdates()
    }
    .onChange(of: appState.showPreviewSphere) {
        previewSphere?.isEnabled = appState.showPreviewSphere
    }
    .gesture(SpatialTapGesture().targetedToAnyEntity().onEnded { event in
        if event.entity == previewSphere {
            Task {
                // To place a sphere you need to:
                // 1. Create a world anchor with the translation of that offset transform and add the anchor to the world tracking provider.
                // 2. Create the sphere's geometry in `processWorldTrackingUpdates()` after you have successfully added the world anchor.
                await appState.addWorldAnchor(at: event.entity.transformMatrix(relativeTo: nil))
                appState.showPreviewSphere = false
            }
        }
    })
}

}

extension WorldAndRoomView { /// Runs a given function at an approximate frequency. func run(_ function: @escaping () -> Void, withFrequency freqHz: UInt64) -> Task<Void, Never> { return Task { while true { if Task.isCancelled { return }

            // Sleeps for 1 s / Hz before calling the function.
            let nanoSecondsToSleep: UInt64 = NSEC_PER_SEC / freqHz
            do {
                try await Task.sleep(nanoseconds: nanoSecondsToSleep)
            } catch {
                // Sleep fails when the Task is in a canceled state. Exit the loop.
                return
            }
            
            function()
        }
    }
}

}

url: https://developer.apple.com/documentation/healthkit/visualizing_healthkit_state_of_mind_in_visionos title: Visualizing HealthKit State of Mind in visionOS description: Learn how to incorporate HealthKit State of Mind into your app and visualize the data in visionOS. code_title: HKStateOfMindDataSampleApp.swift code_sample: import SwiftUI import HealthKit import EventKit

@main struct HKStateOfMindDataSampleApp: App {

let healthStore = HealthStore.shared.healthStore

@State var calendars = Calendars(calendarModels: [])

/* Authorization */
@State var eventsAuthorized: Bool?

@State var toggleHealthDataAuthorization = false
@State var healthDataAuthorized: Bool?

var body: some Scene {

#if os(visionOS) ReflectionScene(calendars: calendars) #endif WindowGroup { TabsView(initialSelection: .today, calendars: $calendars, eventsAuthorized: $eventsAuthorized, toggleHealthDataAuthorization: $toggleHealthDataAuthorization, healthDataAuthorized: $healthDataAuthorized) .onAppear { Task { do { // Request authorization. self.eventsAuthorized = try await CalendarFetcher.shared.requestAuthorization() // Fetch calendars.

【1†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

public func exitExploration() { if let bodies = RobotProvider.shared.robotParts[.body] { for body in bodies { body.stopAllAnimations() } }

    robot?.animationState = .idle
    robot?.head.removeFromParent()
    robot?.body.removeFromParent()
    robot?.backpack.removeFromParent()
    
    robot?.head.transform.translation = .zero
    robot?.head.transform.rotation = simd_quatf()
    robot?.body.transform.translation = .zero
    robot?.body.transform.rotation = simd_quatf()
    robot?.backpack.transform.translation = .zero
    robot?.backpack.transform.rotation = simd_quatf()
   
    if let skeleton = robot?.body.findEntity(named: "rig_grp") {
        skeleton.jointPinComponent = nil
    }
    
    let children = explorationRoot.children
    for child in children {
        child.removeFromParent()
    }
    
    explorationEnvironment = nil

    restoreRobotInCreator()
    phase = .playing
}

}

url: https://developer.apple.com/documentation/visionOS/BOT-anist title: BOT-anist description: Build a multiplatform app that uses windows, volumes, and animations to create a robot botanist’s greenhouse. code_title: AppState.swift code_sample: import Foundation import RealityKit import BOTanistAssets import SwiftUI import Spatial

/// An enumeration that tracks the current phase of the app. public enum AppPhase: CaseIterable, Codable, Identifiable, Sendable { case waitingToStart // Waiting to start the game case loadingAssets // Loading assets from the Reality Composer Pro project case playing // Creating the robot. case exploration // Exploring the volume.

public var id: Self { self }

}

/// An object that maintains app-wide state. @Observable @MainActor public class AppState {

/// The root entity for the reality view in which robot creation happens.
var creationRoot = Entity()
/// The root entity for the exploration `RealityView`.
var explorationRoot = Entity()

/// The parent entity for the exploration environment.
var explorationEnvironment: Entity? = nil

var selectedBodyIndex: Int = 1
    
var robotData: RobotData!

/// A Boolean value that indicates whether the robot is celebrating after propagating every plant.
var celebrating: Bool = false

let materialColorParameterName = "mat_switch"
let materialLightsParameterName = "light_switch"
let materialFaceParameterName = "face_switch"

/// The finished and built robot. Intialized after creation phase.
var robot: RobotCharacter? = nil

/// The current phase of the app.
var phase = AppPhase.waitingToStart

/// The orientation of the robot model in the creation screen.
var robotCreationOrientation: Rotation3D = Rotation3D()

var isRotating = false

/// The camera establishing the rendering perspective for the creation screen `RealityView` for platforms other than visionOS.
let robotCamera = PerspectiveCamera()
/// The camera establishing the rendering perspective for the exploration screen `RealityView` for platforms other than visionOS.

【2†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

public func exitExploration() { if let bodies = RobotProvider.shared.robotParts[.body] { for body in bodies { body.stopAllAnimations() } }

    robot?.animationState = .idle
    robot?.head.removeFromParent()
    robot?.body.removeFromParent()
    robot?.backpack.removeFromParent()
    
    robot?.head.transform.translation = .zero
    robot?.head.transform.rotation = simd_quatf()
    robot?.body.transform.translation = .zero
    robot?.body.transform.rotation = simd_quatf()
    robot?.backpack.transform.translation = .zero
    robot?.backpack.transform.rotation = simd_quatf()
   
    if let skeleton = robot?.body.findEntity(named: "rig_grp") {
        skeleton.jointPinComponent = nil
    }
    
    let children = explorationRoot.children
    for child in children {
        child.removeFromParent()
    }
    
    explorationEnvironment = nil

    restoreRobotInCreator()
    phase = .playing
}

}

url: https://developer.apple.com/documentation/visionos/bot-anist title: BOT-anist description: Build a multiplatform app that uses windows, volumes, and animations to create a robot botanist’s greenhouse. code_title: AppState.swift code_sample: import Foundation import RealityKit import BOTanistAssets import SwiftUI import Spatial

/// An enumeration that tracks the current phase of the app. public enum AppPhase: CaseIterable, Codable, Identifiable, Sendable { case waitingToStart // Waiting to start the game case loadingAssets // Loading assets from the Reality Composer Pro project case playing // Creating the robot. case exploration // Exploring the volume.

public var id: Self { self }

}

/// An object that maintains app-wide state. @Observable @MainActor public class AppState {

/// The root entity for the reality view in which robot creation happens.
var creationRoot = Entity()
/// The root entity for the exploration `RealityView`.
var explorationRoot = Entity()

/// The parent entity for the exploration environment.
var explorationEnvironment: Entity? = nil

var selectedBodyIndex: Int = 1
    
var robotData: RobotData!

/// A Boolean value that indicates whether the robot is celebrating after propagating every plant.
var celebrating: Bool = false

let materialColorParameterName = "mat_switch"
let materialLightsParameterName = "light_switch"
let materialFaceParameterName = "face_switch"

/// The finished and built robot. Intialized after creation phase.
var robot: RobotCharacter? = nil

/// The current phase of the app.
var phase = AppPhase.waitingToStart

/// The orientation of the robot model in the creation screen.
var robotCreationOrientation: Rotation3D = Rotation3D()

var isRotating = false

/// The camera establishing the rendering perspective for the creation screen `RealityView` for platforms other than visionOS.
let robotCamera = PerspectiveCamera()
/// The camera establishing the rendering perspective for the exploration screen `RealityView` for platforms other than visionOS.

【3†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

await appState.queryWorldSensingAuthorization() } } else { // Leave the immersive space if this view is no longer active; // the controls in this view pair up with the immersive space to drive the placement experience. if appState.immersiveSpaceOpened { Task { await dismissImmersiveSpace() appState.didLeaveImmersiveSpace() } } } } .onChange(of: appState.providersStoppedWithError, { _, providersStoppedWithError in // Immediately close the immersive space if there was an error. if providersStoppedWithError { if appState.immersiveSpaceOpened { Task { await dismissImmersiveSpace() appState.didLeaveImmersiveSpace() } }

            appState.providersStoppedWithError = false
        }
    })
    .task {
        // Request authorization before the user attempts to open the immersive space;
        // this gives the app the opportunity to respond gracefully if authorization isn’t granted.
        if appState.allRequiredProvidersAreSupported {
            await appState.requestWorldSensingAuthorization()
        }
    }
    .task {
        // Monitors changes in authorization. For example, the user may revoke authorization in Settings.
        await appState.monitorSessionEvents()
    }
}

}

#Preview(windowStyle: .plain) { HStack { VStack { HomeView(appState: AppState.previewAppState(), modelLoader: ModelLoader(progress: 0.5), immersiveSpaceIdentifier: "A") HomeView(appState: AppState.previewAppState(), modelLoader: ModelLoader(progress: 1.0), immersiveSpaceIdentifier: "A") } VStack { HomeView(appState: AppState.previewAppState(immersiveSpaceOpened: true), modelLoader: ModelLoader(progress: 1.0), immersiveSpaceIdentifier: "A") } } }

url: https://developer.apple.com/documentation/visionos/placing-content-on-detected-planes title: Placing content on detected planes description: Detect horizontal surfaces like tables and floors, as well as vertical planes like walls and doors. code_title: InfoLabel.swift code_sample: import SwiftUI

struct InfoLabel: View { let appState: AppState

var body: some View {
    Text(infoMessage)
        .font(.subheadline)
        .multilineTextAlignment(.center)
}

var infoMessage: String {
    if !appState.allRequiredProvidersAreSupported {
        return "This app requires functionality that isn’t supported in Simulator."
    } else if !appState.allRequiredAuthorizationsAreGranted {
        return "This app is missing necessary authorizations. You can change this in Settings > Privacy & Security."
    } else {
        return "Place and move 3D models in your physical environment. The system maintains their placement across app launches."
    }
}

}

#Preview(windowStyle: .plain) { InfoLabel(appState: AppState.previewAppState()) .frame(width: 300) .padding(.horizontal, 40.0) .padding(.vertical, 20.0) .glassBackgroundEffect() }

url: https://developer.apple.com/documentation/visionos/placing-content-on-detected-planes title: Placing content on detected planes description: Detect horizontal surfaces like tables and floors, as well as vertical planes like walls and doors.

【4†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

if appState.immersiveSpaceOpened { Task { await dismissImmersiveSpace() appState.didLeaveImmersiveSpace() } } } } } }

url: https://developer.apple.com/documentation/visionos/placing-content-on-detected-planes title: Placing content on detected planes description: Detect horizontal surfaces like tables and floors, as well as vertical planes like walls and doors. code_title: AppState.swift code_sample: import Foundation import ARKit import RealityKit

@Observable class AppState { var immersiveSpaceOpened: Bool { placementManager != nil } private(set) weak var placementManager: PlacementManager? = nil

private(set) var placeableObjectsByFileName: [String: PlaceableObject] = [:]
private(set) var modelDescriptors: [ModelDescriptor] = []
var selectedFileName: String?

func immersiveSpaceOpened(with manager: PlacementManager) {
    placementManager = manager
}

func didLeaveImmersiveSpace() {
    // Remember which placed object is attached to which persistent world anchor when leaving the immersive space.
    if let placementManager {
        placementManager.saveWorldAnchorsObjectsMapToDisk()
        
        // Stop the providers. The providers that just ran in the
        // immersive space are paused now, but the session doesn’t need them anymore.
        // When the user reenters the immersive space, the app runs a new set of providers.
        arkitSession.stop()
    }
    placementManager = nil
}

func setPlaceableObjects(_ objects: [PlaceableObject]) {
    placeableObjectsByFileName = objects.reduce(into: [:]) { map, placeableObject in
        map[placeableObject.descriptor.fileName] = placeableObject
    }

    // Sort descriptors alphabetically.
    modelDescriptors = objects.map { $0.descriptor }.sorted { lhs, rhs in
        lhs.displayName < rhs.displayName
    }

}

// MARK: - ARKit state

var arkitSession = ARKitSession()
var providersStoppedWithError = false
var worldSensingAuthorizationStatus = ARKitSession.AuthorizationStatus.notDetermined

var allRequiredAuthorizationsAreGranted: Bool {
    worldSensingAuthorizationStatus == .allowed
}

var allRequiredProvidersAreSupported: Bool {
    WorldTrackingProvider.isSupported && PlaneDetectionProvider.isSupported
}

var canEnterImmersiveSpace: Bool {
    allRequiredAuthorizationsAreGranted && allRequiredProvidersAreSupported
}

func requestWorldSensingAuthorization() async {
    let authorizationResult = await arkitSession.requestAuthorization(for: [.worldSensing])
    worldSensingAuthorizationStatus = authorizationResult[.worldSensing]!
}

func queryWorldSensingAuthorization() async {
    let authorizationResult = await arkitSession.queryAuthorization(for: [.worldSensing])
    worldSensingAuthorizationStatus = authorizationResult[.worldSensing]!
}

【5†WWDC24-visionOS.pdf†file-hRhjSKKSkzKOEjugORZ6BAMa】

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

【6†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

await appState.queryWorldSensingAuthorization() } } else { // Leave the immersive space if this view is no longer active; // the controls in this view pair up with the immersive space to drive the placement experience. if appState.immersiveSpaceOpened { Task { await dismissImmersiveSpace() appState.didLeaveImmersiveSpace() } } } } .onChange(of: appState.providersStoppedWithError, { _, providersStoppedWithError in // Immediately close the immersive space if there was an error. if providersStoppedWithError { if appState.immersiveSpaceOpened { Task { await dismissImmersiveSpace() appState.didLeaveImmersiveSpace() } }

            appState.providersStoppedWithError = false
        }
    })
    .task {
        // Request authorization before the user attempts to open the immersive space;
        // this gives the app the opportunity to respond gracefully if authorization isn’t granted.
        if appState.allRequiredProvidersAreSupported {
            await appState.requestWorldSensingAuthorization()
        }
    }
    .task {
        // Monitors changes in authorization. For example, the user may revoke authorization in Settings.
        await appState.monitorSessionEvents()
    }
}

}

#Preview(windowStyle: .plain) { HStack { VStack { HomeView(appState: AppState.previewAppState(), modelLoader: ModelLoader(progress: 0.5), immersiveSpaceIdentifier: "A") HomeView(appState: AppState.previewAppState(), modelLoader: ModelLoader(progress: 1.0), immersiveSpaceIdentifier: "A") } VStack { HomeView(appState: AppState.previewAppState(immersiveSpaceOpened: true), modelLoader: ModelLoader(progress: 1.0), immersiveSpaceIdentifier: "A") } } }

url: https://developer.apple.com/documentation/visionos/tracking-points-in-world-space title: Tracking specific points in world space description: Retrieve the position and orientation of anchors your app stores in ARKit. code_title: InfoLabel.swift code_sample: import SwiftUI

struct InfoLabel: View { let appState: AppState

var body: some View {
    Text(infoMessage)
        .font(.subheadline)
        .multilineTextAlignment(.center)
}

var infoMessage: String {
    if !appState.allRequiredProvidersAreSupported {
        return "This app requires functionality that isn’t supported in Simulator."
    } else if !appState.allRequiredAuthorizationsAreGranted {
        return "This app is missing necessary authorizations. You can change this in Settings > Privacy & Security."
    } else {
        return "Place and move 3D models in your physical environment. The system maintains their placement across app launches."
    }
}

}

#Preview(windowStyle: .plain) { InfoLabel(appState: AppState.previewAppState()) .frame(width: 300) .padding(.horizontal, 40.0) .padding(.vertical, 20.0) .glassBackgroundEffect() }

url: https://developer.apple.com/documentation/visionos/tracking-points-in-world-space title: Tracking specific points in world space description: Retrieve the position and orientation of anchors your app stores in ARKit.

【7†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

if appState.immersiveSpaceOpened { Task { await dismissImmersiveSpace() appState.didLeaveImmersiveSpace() } } } } } }

url: https://developer.apple.com/documentation/visionos/tracking-points-in-world-space title: Tracking specific points in world space description: Retrieve the position and orientation of anchors your app stores in ARKit. code_title: AppState.swift code_sample: import Foundation import ARKit import RealityKit

@Observable class AppState { var immersiveSpaceOpened: Bool { placementManager != nil } private(set) weak var placementManager: PlacementManager? = nil

private(set) var placeableObjectsByFileName: [String: PlaceableObject] = [:]
private(set) var modelDescriptors: [ModelDescriptor] = []
var selectedFileName: String?

func immersiveSpaceOpened(with manager: PlacementManager) {
    placementManager = manager
}

func didLeaveImmersiveSpace() {
    // Remember which placed object is attached to which persistent world anchor when leaving the immersive space.
    if let placementManager {
        placementManager.saveWorldAnchorsObjectsMapToDisk()
        
        // Stop the providers. The providers that just ran in the
        // immersive space are paused now, but the session doesn’t need them anymore.
        // When the user reenters the immersive space, the app runs a new set of providers.
        arkitSession.stop()
    }
    placementManager = nil
}

func setPlaceableObjects(_ objects: [PlaceableObject]) {
    placeableObjectsByFileName = objects.reduce(into: [:]) { map, placeableObject in
        map[placeableObject.descriptor.fileName] = placeableObject
    }

    // Sort descriptors alphabetically.
    modelDescriptors = objects.map { $0.descriptor }.sorted { lhs, rhs in
        lhs.displayName < rhs.displayName
    }

}

// MARK: - ARKit state

var arkitSession = ARKitSession()
var providersStoppedWithError = false
var worldSensingAuthorizationStatus = ARKitSession.AuthorizationStatus.notDetermined

var allRequiredAuthorizationsAreGranted: Bool {
    worldSensingAuthorizationStatus == .allowed
}

var allRequiredProvidersAreSupported: Bool {
    WorldTrackingProvider.isSupported && PlaneDetectionProvider.isSupported
}

var canEnterImmersiveSpace: Bool {
    allRequiredAuthorizationsAreGranted && allRequiredProvidersAreSupported
}

func requestWorldSensingAuthorization() async {
    let authorizationResult = await arkitSession.requestAuthorization(for: [.worldSensing])
    worldSensingAuthorizationStatus = authorizationResult[.worldSensing]!
}

func queryWorldSensingAuthorization() async {
    let authorizationResult = await arkitSession.queryAuthorization(for: [.worldSensing])
    worldSensingAuthorizationStatus = authorizationResult[.worldSensing]!
}

【8†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

code_title: AppModel.swift code_sample: import SwiftUI

/// Maintains the app-wide state. @Observable public class AppModel { public var showImmersiveSpace = false public var immersiveSpaceIsShown = false }

url: https://developer.apple.com/documentation/realitykit/presenting-an-artists-scene title: Presenting an artist’s scene description: Display a scene from Reality Composer Pro in visionOS. code_title: ArtistWorkflowExampleApp.swift code_sample: import SwiftUI

@main struct ArtistWorkflowExampleApp: App {

@State private var appModel = AppModel()

@Environment(\.dismissImmersiveSpace) var dismissImmersiveSpace
@Environment(\.openImmersiveSpace) private var openImmersiveSpace

var body: some Scene {
    WindowGroup {
        ContentView()
            .environment(appModel)
            .onChange(of: appModel.showImmersiveSpace) { _, newValue in
                Task { @MainActor in
                    if newValue {
                        switch await openImmersiveSpace(id: "ImmersiveSpace") {
                        case .opened:
                            appModel.immersiveSpaceIsShown = true
                        case .error, .userCancelled:
                            fallthrough
                        @unknown default:
                            appModel.immersiveSpaceIsShown = false
                            appModel.showImmersiveSpace = false
                        }
                    } else if appModel.immersiveSpaceIsShown {
                        await dismissImmersiveSpace()
                    }
                }
            }
    }.windowStyle(.plain)
    .windowResizability(.contentSize)
    .defaultSize(width: 600, height: 300)

    ImmersiveSpace(id: "ImmersiveSpace") {
        ImmersiveView()
            .environment(appModel)
    }.immersionStyle(selection: .constant(.full), in: .full)
}

}

url: https://developer.apple.com/documentation/realitykit/presenting-an-artists-scene title: Presenting an artist’s scene description: Display a scene from Reality Composer Pro in visionOS. code_title: ContentView.swift code_sample: import SwiftUI import RealityKit import RealityKitContent

extension Image { init(resource name: String, ofType type: String) { guard let path = Bundle.main.path(forResource: name, ofType: type), let image = UIImage(contentsOfFile: path) else { self.init(name) return } self.init(uiImage: image) } }

struct ContentView: View { @Environment(.scenePhase) private var scenePhase @Environment(.dismissImmersiveSpace) var dismissImmersiveSpace @Environment(AppModel.self) var appModel

var body: some View {
    VStack(alignment: .trailing) {
        if appModel.immersiveSpaceIsShown {
            EmptyView()
        } else {
            Image(resource: "environment", ofType: "png")
            .resizable()
            .aspectRatio(contentMode: .fit)
            .glassBackgroundEffect()
        }
    }
    .onChange(of: scenePhase) { _, newPhase in
        Task { @MainActor in
            if newPhase == .background {
                appModel.showImmersiveSpace = false
            }
        }
    }
    .toolbar {
        ToolbarItemGroup(placement: .bottomOrnament) {
            VStack(spacing: 12) {

                Button {
                    appModel.showImmersiveSpace.toggle()
                } label: {
                    Text(appModel.showImmersiveSpace ?

【9†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

Constants.compactVideoCardWidth : Constants.videoCardWidth) .clipShape(.rect(cornerRadius: Constants.cornerRadius)) #if os(iOS) || os(visionOS) .hoverEffect() #endif

    case .upNext:
        PosterCard(image: image, title: video.localizedName)
            .frame(width: Constants.upNextVideoCardWidth)
            .clipShape(.rect(cornerRadius: Constants.cornerRadius))
            #if os(iOS) || os(visionOS)
            .hoverEffect()
            #endif
        
    case .full:
        VStack {
            image.scaledToFill()
            
            InfoView(video: video)
        }
        #if os(macOS)
        .background(.quaternary)
        #else
        .background(.ultraThinMaterial)
        #endif
        #if os(iOS) || os(visionOS)
        .hoverEffect()
        #endif
        .frame(width: isCompact ? Constants.compactVideoCardWidth : Constants.videoCardWidth)
        .clipShape(.rect(cornerRadius: Constants.cornerRadius))
        
    case .grid:
        PosterCard(image: image, title: video.localizedName)
            #if os(iOS) || os(visionOS)
            .hoverEffect()
            #endif
        
    case .stack:
        HStack(spacing: 0) {
            image
                .scaledToFill()
                .frame(maxWidth: isCompact ? Constants.stackImageCompactWidth : Constants.stackImageWidth)
                .cornerRadius(Constants.cornerRadius)
                .padding([.leading, .vertical], Constants.cardPadding)
            
            InfoView(video: video)
        }
        #if os(macOS)
        .background(.quaternary)
        #else
        .background(.ultraThinMaterial)
        #endif
        #if os(iOS) || os(visionOS)
        .hoverEffect()
        #endif
        .cornerRadius(Constants.cornerRadius)
    }
}

}

#Preview("Full", traits: .previewData) { @Previewable @Query(sort: \Video.id) var videos: [Video] return VideoCardView(video: videos.first!, style: .full) .frame(height: 350) }

#Preview("Grid", traits: .previewData) { @Previewable @Query(sort: \Video.id) var videos: [Video] return VideoCardView(video: videos.first!, style: .grid) .frame(width: 200, height: 200) }

#Preview("Half", traits: .previewData) { @Previewable @Query(sort: \Video.id) var videos: [Video] return VideoCardView(video: videos.first!, style: .half) .frame(width: 200, height: 200) }

#Preview("Stack", traits: .previewData) { @Previewable @Query(sort: \Video.id) var videos: [Video] return VideoCardView(video: videos.first!, style: .stack) .frame(height: 200) }

#Preview("UpNext", traits: .previewData) { @Previewable @Query(sort: \Video.id) var videos: [Video] return VideoCardView(video: videos.first!, style: .upNext) .frame(height: 150) }

url: https://developer.apple.com/documentation/swiftui/enhancing-your-app-content-with-tab-navigation title: Enhancing your app’s content with tab navigation description: Keep your app content front and center while providing quick access to navigation using the tab bar. code_title: VideoInfoView.swift code_sample: import SwiftUI import SwiftData

/// A view that displays information about a video including its title, description, and genre.

【10†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

code_title: ObjectPlacementApp.swift code_sample: import SwiftUI

private enum UIIdentifier { static let immersiveSpace = "Object Placement" }

@main @MainActor struct ObjectPlacementApp: App { @State private var appState = AppState() @State private var modelLoader = ModelLoader()

@Environment(\.dismissImmersiveSpace) private var dismissImmersiveSpace
@Environment(\.scenePhase) private var scenePhase

var body: some SwiftUI.Scene {
    WindowGroup {
        HomeView(
            appState: appState,
            modelLoader: modelLoader,
            immersiveSpaceIdentifier: UIIdentifier.immersiveSpace
        )
            .task {
                await modelLoader.loadObjects()
                appState.setPlaceableObjects(modelLoader.placeableObjects)
            }
    }
    .windowResizability(.contentSize)
    .windowStyle(.plain)

    ImmersiveSpace(id: UIIdentifier.immersiveSpace) {
        ObjectPlacementRealityView(appState: appState)
    }
    .onChange(of: scenePhase, initial: true) {
        if scenePhase != .active {
            // Leave the immersive space when the user dismisses the app.
            if appState.immersiveSpaceOpened {
                Task {
                    await dismissImmersiveSpace()
                    appState.didLeaveImmersiveSpace()
                }
            }
        }
    }
}

}

url: https://developer.apple.com/documentation/visionos/placing-content-on-detected-planes title: Placing content on detected planes description: Detect horizontal surfaces like tables and floors, as well as vertical planes like walls and doors. code_title: AppState.swift code_sample: import Foundation import ARKit import RealityKit

@Observable class AppState { var immersiveSpaceOpened: Bool { placementManager != nil } private(set) weak var placementManager: PlacementManager? = nil

private(set) var placeableObjectsByFileName: [String: PlaceableObject] = [:]
private(set) var modelDescriptors: [ModelDescriptor] = []
var selectedFileName: String?

func immersiveSpaceOpened(with manager: PlacementManager) {
    placementManager = manager
}

func didLeaveImmersiveSpace() {
    // Remember which placed object is attached to which persistent world anchor when leaving the immersive space.
    if let placementManager {
        placementManager.saveWorldAnchorsObjectsMapToDisk()
        
        // Stop the providers. The providers that just ran in the
        // immersive space are paused now, but the session doesn’t need them anymore.
        // When the user reenters the immersive space, the app runs a new set of providers.
        arkitSession.stop()
    }
    placementManager = nil
}

func setPlaceableObjects(_ objects: [PlaceableObject]) {
    placeableObjectsByFileName = objects.reduce(into: [:]) { map, placeableObject in
        map[placeableObject.descriptor.fileName] = placeableObject
    }

    // Sort descriptors alphabetically.

【11†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

}

#Preview(windowStyle: .plain) { VStack { TooltipView(text: "Text") } }

url: https://developer.apple.com/documentation/visionos/tracking-points-in-world-space title: Tracking specific points in world space description: Retrieve the position and orientation of anchors your app stores in ARKit. code_title: ObjectPlacementApp.swift code_sample: import SwiftUI

private enum UIIdentifier { static let immersiveSpace = "Object Placement" }

@main @MainActor struct ObjectPlacementApp: App { @State private var appState = AppState() @State private var modelLoader = ModelLoader()

@Environment(\.dismissImmersiveSpace) private var dismissImmersiveSpace
@Environment(\.scenePhase) private var scenePhase

var body: some SwiftUI.Scene {
    WindowGroup {
        HomeView(
            appState: appState,
            modelLoader: modelLoader,
            immersiveSpaceIdentifier: UIIdentifier.immersiveSpace
        )
            .task {
                await modelLoader.loadObjects()
                appState.setPlaceableObjects(modelLoader.placeableObjects)
            }
    }
    .windowResizability(.contentSize)
    .windowStyle(.plain)

    ImmersiveSpace(id: UIIdentifier.immersiveSpace) {
        ObjectPlacementRealityView(appState: appState)
    }
    .onChange(of: scenePhase, initial: true) {
        if scenePhase != .active {
            // Leave the immersive space when the user dismisses the app.
            if appState.immersiveSpaceOpened {
                Task {
                    await dismissImmersiveSpace()
                    appState.didLeaveImmersiveSpace()
                }
            }
        }
    }
}

}

url: https://developer.apple.com/documentation/visionos/tracking-points-in-world-space title: Tracking specific points in world space description: Retrieve the position and orientation of anchors your app stores in ARKit. code_title: AppState.swift code_sample: import Foundation import ARKit import RealityKit

@Observable class AppState { var immersiveSpaceOpened: Bool { placementManager != nil } private(set) weak var placementManager: PlacementManager? = nil

private(set) var placeableObjectsByFileName: [String: PlaceableObject] = [:]
private(set) var modelDescriptors: [ModelDescriptor] = []
var selectedFileName: String?

func immersiveSpaceOpened(with manager: PlacementManager) {
    placementManager = manager
}

func didLeaveImmersiveSpace() {
    // Remember which placed object is attached to which persistent world anchor when leaving the immersive space.
    if let placementManager {
        placementManager.saveWorldAnchorsObjectsMapToDisk()
        
        // Stop the providers. The providers that just ran in the
        // immersive space are paused now, but the session doesn’t need them anymore.
        // When the user reenters the immersive space, the app runs a new set of providers.
        arkitSession.stop()
    }
    placementManager = nil
}

func setPlaceableObjects(_ objects: [PlaceableObject]) {
    placeableObjectsByFileName = objects.reduce(into: [:]) { map, placeableObject in
        map[placeableObject.descriptor.fileName] = placeableObject
    }

    // Sort descriptors alphabetically.

【12†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

540 : 200)

            // If someone closes the main window, dismiss the immersive space. If placing the first piece, ignore it.
            .onChange(of: scenePhase) { _, newPhase in
                Task {
                    if (newPhase == .background || newPhase == .inactive) && appState.isImmersiveViewShown
                        && appState.phase != .placingStartPiece && appState.phase != .draggingStartPiece {
                        appState.resetBoard()
                        appState.goBackToWaiting()
                        await dismissImmersiveSpace()
                        appState.isImmersiveViewShown = false
                    }
                }
            }
            .onChange(of: appState.presentedRide) {
                if appState.presentedRide.isEmpty {
                    withAnimation {
                        // Went back.
                        shouldCancelRide = true
                        appState.resetRideAnimations()
                        appState.addHoverEffectToConnectables()
                        appState.goalPiece?.stopWaterfall()
                        appState.returnToBuildingTrack()
                        appState.isRideRunning = false
                        appState.music = .build
                        appState.updateConnections()
                        appState.updateSelection()
                        appState.goalPiece?.setAllParticleEmittersTo(to: false)
                    }
                } else {
                    // Play.
                    shouldCancelRide = false
                }
                
                Timer.scheduledTimer(withTimeInterval: 0.1, repeats: false) { _ in
                    Task {
                        withAnimation(.easeIn(duration: 1.0)) {
                            if appState.presentedRide.isEmpty {
                                isReducedHeight = false
                            } else {
                                isReducedHeight = true
                            }
                        }
                    }
                }
            }
    }
}

}

#Preview { ContentView() .environment(AppState()) }

url: https://developer.apple.com/documentation/visionos/swift-splash title: Swift Splash description: Use RealityKit to create an interactive ride in visionOS. code_title: EditTrackPieceView.swift code_sample: import SwiftSplashTrackPieces import SwiftUI struct EditTrackPieceView: View { @Environment(AppState.self) var appState @State private var isSelecting = true @Environment(.dismiss) private var dismiss

var body: some View {
    VStack {
        HStack(spacing: 0) {
            Button {
                appState.selectConnectedPieces()
            } label: {
                Text("\(Image(systemName: "plus.square.dashed")) Select Attached",
                     comment: "An action the player can take. Specifier is replaced by a + image.")
                .fontWeight(.semibold)
                .frame(maxWidth: .infinity)
            }
            .padding(.leading, 20)
            .accessibilityElement()
            .accessibilityLabel(Text("Select all ride pieces that connect back to this piece.",
                                     comment: "For accessibility: An action to select certain ride pieces."))
            
            Spacer()
            
            Button(role: .destructive) {
                if let goalPiece = appState.goalPiece {
                    if appState.trackPieceBeingEdited == goalPiece ||
                        appState.additionalSelectedTrackPieces.contains(goalPiece) {
                        goalPiece.removeFromParent()
                    }
                }
                appState.deleteSelectedPieces()
                
            } label: {
                Label {
                    Text("Delete", comment: "An action the user can take on the selected ride piece or pieces.")
                } icon: {
                    Image(systemName: "trash")
                }
                .labelStyle(.iconOnly)
            }
            .disabled(appState.trackPieceBeingEdited == appState.startPiece)
            .accessibilityElement()
            .accessibilityLabel(Text("Delete all selected ride pieces.",
                                     comment: "For accessibility: An action the user can take on the selected ride piece or pieces."))

【13†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

Constants.compactVideoCardWidth : Constants.videoCardWidth) .clipShape(.rect(cornerRadius: Constants.cornerRadius)) #if os(iOS) || os(visionOS) .hoverEffect() #endif

    case .upNext:
        PosterCard(image: image, title: video.localizedName)
            .frame(width: Constants.upNextVideoCardWidth)
            .clipShape(.rect(cornerRadius: Constants.cornerRadius))
            #if os(iOS) || os(visionOS)
            .hoverEffect()
            #endif
        
    case .full:
        VStack {
            image.scaledToFill()
            
            InfoView(video: video)
        }
        #if os(macOS)
        .background(.quaternary)
        #else
        .background(.ultraThinMaterial)
        #endif
        #if os(iOS) || os(visionOS)
        .hoverEffect()
        #endif
        .frame(width: isCompact ? Constants.compactVideoCardWidth : Constants.videoCardWidth)
        .clipShape(.rect(cornerRadius: Constants.cornerRadius))
        
    case .grid:
        PosterCard(image: image, title: video.localizedName)
            #if os(iOS) || os(visionOS)
            .hoverEffect()
            #endif
        
    case .stack:
        HStack(spacing: 0) {
            image
                .scaledToFill()
                .frame(maxWidth: isCompact ? Constants.stackImageCompactWidth : Constants.stackImageWidth)
                .cornerRadius(Constants.cornerRadius)
                .padding([.leading, .vertical], Constants.cardPadding)
            
            InfoView(video: video)
        }
        #if os(macOS)
        .background(.quaternary)
        #else
        .background(.ultraThinMaterial)
        #endif
        #if os(iOS) || os(visionOS)
        .hoverEffect()
        #endif
        .cornerRadius(Constants.cornerRadius)
    }
}

}

#Preview("Full", traits: .previewData) { @Previewable @Query(sort: \Video.id) var videos: [Video] return VideoCardView(video: videos.first!, style: .full) .frame(height: 350) }

#Preview("Grid", traits: .previewData) { @Previewable @Query(sort: \Video.id) var videos: [Video] return VideoCardView(video: videos.first!, style: .grid) .frame(width: 200, height: 200) }

#Preview("Half", traits: .previewData) { @Previewable @Query(sort: \Video.id) var videos: [Video] return VideoCardView(video: videos.first!, style: .half) .frame(width: 200, height: 200) }

#Preview("Stack", traits: .previewData) { @Previewable @Query(sort: \Video.id) var videos: [Video] return VideoCardView(video: videos.first!, style: .stack) .frame(height: 200) }

#Preview("UpNext", traits: .previewData) { @Previewable @Query(sort: \Video.id) var videos: [Video] return VideoCardView(video: videos.first!, style: .upNext) .frame(height: 150) }

url: https://developer.apple.com/documentation/visionos/destination-video title: Destination Video description: Leverage SwiftUI to build an immersive media experience in a multiplatform app. code_title: VideoInfoView.swift code_sample: import SwiftUI import SwiftData

/// A view that displays information about a video including its title, description, and genre.

【14†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

var lowerLimit: Int { (model.selectedDayLessons.count) / 2 }

/*
    The system calls this when the user dismiss the event edit view
    controller. The app disables the booking button and unselects the current
    lesson time slot.
*/
func didDismissEventEditController() {
    selection = nil
}

/*
    The app updates its UI with a list of lesson time slots for the selected
    day.
*/
func refreshLessonsAction() {
    model.updateSelectedDayLessons()
    selection = nil
}

/*
    The system calls this when the user taps the booking button.
    The app creates an event with the details of the currently selected
    lesson.
 */
func bookLessonAction() {
    Task {
        if #unavailable(iOS 17) {
            do {
                guard try await store.requestAccess(to: .event) else {
                    selection = nil
                    let message = "The app doesn't have permission to access calendar data. Please grant the app access to Calendar in Settings."
                    showError(message, title: "Calendar access denied")
                    return
                }
            } catch {
                selection = nil
                showError(error.localizedDescription, title: "Failed to request calendar access")
                return
            }
        }
        
        if let selection = selection {
           selectedEvent = selection.eventWithDate(model.selectedDate, store: store)
        }
        
        showEventEditViewController.toggle()
    }
}

@ViewBuilder
func selectTimeSlot() -> some View {
    VStack {
        Text("Select a time slot")
            .font(.headline)
            .foregroundStyle(Color.primary)
            .frame(maxWidth: .infinity, alignment: .leading)
        Divider()
        .frame(height: 2)
    }
    .padding()
}

@ViewBuilder
/// Set up the date picker.
private func buildDatePicker() -> some View {
    if #available(iOS 17.0, *) {
        DatePickerView(displayDate: $model.selectedDate)
        .onChange(of: model.selectedDate, refreshLessonsAction)
    } else {
        // Fall back on earlier versions.
        DatePickerView(displayDate: $model.selectedDate)
        .onChange(of: model.selectedDate) { newvalue in
            refreshLessonsAction()
        }
    }
}

@ViewBuilder
/*
    The DropIn lessons app creates and saves events, which doesn't require
    accessing calendar data. Thus, the app has no need for prompting the
    user for Calendar authorization. The app presents the event edit view
    controller when the user taps the booking button. The controller takes
    an event created from the currently selected lesson and an event store
    as parameters. EKEventEditViewController objects render their content
    out-of-process. These controllers allow apps to present an editor for
    adding, editing, and deleting events without prompting the user for
    access. The editor also displays all the user's calendars.

【15†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

Constants.compactVideoCardWidth : Constants.videoCardWidth) .clipShape(.rect(cornerRadius: Constants.cornerRadius)) #if os(iOS) || os(visionOS) .hoverEffect() #endif

    case .upNext:
        PosterCard(image: image, title: video.localizedName)
            .frame(width: Constants.upNextVideoCardWidth)
            .clipShape(.rect(cornerRadius: Constants.cornerRadius))
            #if os(iOS) || os(visionOS)
            .hoverEffect()
            #endif
        
    case .full:
        VStack {
            image.scaledToFill()
            
            InfoView(video: video)
        }
        #if os(macOS)
        .background(.quaternary)
        #else
        .background(.ultraThinMaterial)
        #endif
        #if os(iOS) || os(visionOS)
        .hoverEffect()
        #endif
        .frame(width: isCompact ? Constants.compactVideoCardWidth : Constants.videoCardWidth)
        .clipShape(.rect(cornerRadius: Constants.cornerRadius))
        
    case .grid:
        PosterCard(image: image, title: video.localizedName)
            #if os(iOS) || os(visionOS)
            .hoverEffect()
            #endif
        
    case .stack:
        HStack(spacing: 0) {
            image
                .scaledToFill()
                .frame(maxWidth: isCompact ? Constants.stackImageCompactWidth : Constants.stackImageWidth)
                .cornerRadius(Constants.cornerRadius)
                .padding([.leading, .vertical], Constants.cardPadding)
            
            InfoView(video: video)
        }
        #if os(macOS)
        .background(.quaternary)
        #else
        .background(.ultraThinMaterial)
        #endif
        #if os(iOS) || os(visionOS)
        .hoverEffect()
        #endif
        .cornerRadius(Constants.cornerRadius)
    }
}

}

#Preview("Full", traits: .previewData) { @Previewable @Query(sort: \Video.id) var videos: [Video] return VideoCardView(video: videos.first!, style: .full) .frame(height: 350) }

#Preview("Grid", traits: .previewData) { @Previewable @Query(sort: \Video.id) var videos: [Video] return VideoCardView(video: videos.first!, style: .grid) .frame(width: 200, height: 200) }

#Preview("Half", traits: .previewData) { @Previewable @Query(sort: \Video.id) var videos: [Video] return VideoCardView(video: videos.first!, style: .half) .frame(width: 200, height: 200) }

#Preview("Stack", traits: .previewData) { @Previewable @Query(sort: \Video.id) var videos: [Video] return VideoCardView(video: videos.first!, style: .stack) .frame(height: 200) }

#Preview("UpNext", traits: .previewData) { @Previewable @Query(sort: \Video.id) var videos: [Video] return VideoCardView(video: videos.first!, style: .upNext) .frame(height: 150) }

url: https://developer.apple.com/documentation/visionos/building-an-immersive-media-viewing-experience title: Building an immersive media viewing experience description: Add a deeper level of immersion to media playback in your app with RealityKit and Reality Composer Pro. code_title: VideoInfoView.swift code_sample: import SwiftUI import SwiftData

/// A view that displays information about a video including its title, description, and genre.

【16†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

} } }

/// Creates a world anchor with the input transform and adds the anchor to the world tracking provider.
func addWorldAnchor(at transform: simd_float4x4) async {
    
    let worldAnchor = WorldAnchor(originFromAnchorTransform: transform)
    do {
        try await self.worldTracking.addAnchor(worldAnchor)
    } catch {
        // Adding world anchors can fail, for example when you reach the limit
        // for total world anchors per app.
        logger.error("Failed to add world anchor \(worldAnchor.id) with error: \(error).")
    }
}

}

url: https://developer.apple.com/documentation/arkit/arkit_in_visionos/building_local_experiences_with_room_tracking title: Building local experiences with room tracking description: Use room tracking in visionOS to provide custom interactions with physical spaces. code_title: ARKitRoomTrackingApp.swift code_sample: import OSLog import SwiftUI

let immersiveSpace = "ImmersiveSpace"

/// The entry point for the app. @main @MainActor struct ARKitRoomTrackingApp: App {

@State private var appState = AppState()

var body: some Scene {
    WindowGroup {
        ContentView()
            .environment(appState)
    }.defaultSize(CGSize(width: 800, height: 400))
    
    ImmersiveSpace(id: immersiveSpace) {
        WorldAndRoomView()
            .environment(appState)
    }
}

}

@MainActor let logger = Logger(subsystem: "com.example.apple-samplecode.arkitroomtracking.ARKitRoomTracking", category: "general")

url: https://developer.apple.com/documentation/arkit/arkit_in_visionos/building_local_experiences_with_room_tracking title: Building local experiences with room tracking description: Use room tracking in visionOS to provide custom interactions with physical spaces. code_title: ContentView.swift code_sample: import SwiftUI import RealityKit

/// The interface of the app. /// /// This view opens the immersive space and starts room tracking. struct ContentView: View { @Environment(.scenePhase) private var scenePhase

@Environment(\.openImmersiveSpace) var openImmersiveSpace
@Environment(\.dismissImmersiveSpace) var dismissImmersiveSpace

@Environment(AppState.self) var appState

@State private var visualization = "None"
var modes = ["None", "Occlusion", "Wall"]

var body: some View {
    Group {
        if appState.errorState != .noError {
            errorView
        } else if appState.isImmersive {
            viewWhileImmersed
        } else {
            viewWhileNonImmersed
        }
    }
    .padding()
    .frame(width: 600)
    .onChange(of: scenePhase) {
        if scenePhase != .active && appState.isImmersive {
            Task {
                await dismissImmersiveSpace()
                appState.isImmersive = false
                appState.showPreviewSphere = false
            }
        }
    }
    .onChange(of: appState.errorState) {
        if appState.errorState != .noError && appState.isImmersive {
            Task {
                await dismissImmersiveSpace()
                appState.isImmersive = false
                appState.showPreviewSphere = false
            }
        }
    }
}

@MainActor var viewWhileNonImmersed: some View {
    VStack {
        Spacer()
        Text("Enter the immersive space to start room tracking.")

【17†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

code_title: SpaceshipApp.swift code_sample: import SwiftUI import RealityKit

@main struct SpaceshipApp: App {

@State var appModel = AppModel()

#if os(visionOS) @Environment(.openWindow) var openWindow @Environment(.dismissWindow) var dismissWindow @Environment(.openImmersiveSpace) var openImmersiveSpace @Environment(.dismissImmersiveSpace) var dismissImmersiveSpace

var body: some SwiftUI.Scene {
    Group {
        WindowGroup {
            MenuView(appModel: appModel)
                .fixedSize()
        }
        .windowResizability(.contentSize)

        WindowGroup(id: "Hangar") {
            HangarView()
                .onDisappear {
                    appModel.isPresentingHangar = false
                }
                .fixedSize()
        }
        .windowStyle(.volumetric)

        WindowGroup(id: "AudioMixer") {
            AudioMixerView(mixer: appModel.audioMixer)
                .onDisappear {
                    appModel.isPresentingAudioMixer = false
                }
                .frame(width: 400)
        }
        .windowResizability(.contentSize)

#if targetEnvironment(simulator) WindowGroup(id: "ShipControl") { SimulatorShipControlView(controlParameters: appModel.shipControlParameters) } .windowResizability(.contentSize) #endif

        ImmersiveSpace(id: "FlightSchool") {
            FlightSchoolView()
        }
        .immersionStyle(selection: .constant(.mixed), in: .mixed)

        ImmersiveSpace(id: "ImmersiveSpace") {
            ImmersiveView()
                .environment(appModel)
        }
        .immersionStyle(selection: $appModel.immersionStyle, in: .mixed, .progressive)
    }
    .onChange(of: appModel.wantsToPresentImmersiveSpace) {
        appModel.isPresentingImmersiveSpace = true
    }
    .onChange(of: appModel.isPresentingImmersiveSpace) {
        Task {
            if appModel.isPresentingImmersiveSpace {
                switch await openImmersiveSpace(id: "ImmersiveSpace") {
                case .opened:
                    appModel.isPresentingImmersiveSpace = true
                case .error, .userCancelled:
                    fallthrough
                @unknown default:
                    appModel.isPresentingImmersiveSpace = false
                }

#if targetEnvironment(simulator) openWindow(id: "ShipControl") #endif } else { await dismissImmersiveSpace()

#if targetEnvironment(simulator) dismissWindow(id: "ShipControl") #endif } } } .onChange(of: appModel.isPresentingHangar) { if appModel.isPresentingHangar { openWindow(id: "Hangar") } else { dismissWindow(id: "Hangar") } } .onChange(of: appModel.isPresentingFlightSchool) { Task { if appModel.isPresentingFlightSchool { await openImmersiveSpace(id: "FlightSchool") } else { await dismissImmersiveSpace() } } } } #endif

#if os(iOS)

@State var isMenuExpanded: Bool = true

var body: some SwiftUI.Scene {
    Group {
        WindowGroup {
            ZStack {
                if appModel.isPresentingImmersiveSpace {
                    ZStack {
                        ImmersiveView()
                            .environment(appModel)

                        MultiTouchControlView(controlParameters: appModel.shipControlParameters)
                    }
                }

                if appModel.

【18†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

}

url: https://developer.apple.com/documentation/visionos/building-an-immersive-media-viewing-experience title: Building an immersive media viewing experience description: Add a deeper level of immersion to media playback in your app with RealityKit and Reality Composer Pro. code_title: Package.swift code_sample: // swift-tools-version:6.0 /* See the LICENSE.txt file for this sample’s licensing information.

Abstract: Extensions to the Studio asset. */

// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package( name: "Studio", platforms: [ .visionOS(.v2), .macOS(.v15), .iOS(.v18) ], products: [ .library( name: "Studio", targets: ["Studio"]) ], dependencies: [ ], targets: [ .target( name: "Studio", dependencies: []) ] )

url: https://developer.apple.com/documentation/visionos/building-an-immersive-media-viewing-experience title: Building an immersive media viewing experience description: Add a deeper level of immersion to media playback in your app with RealityKit and Reality Composer Pro. code_title: Studio.swift code_sample: import Foundation

/// Bundle for the Studio project. public let studioBundle = Bundle.module

url: https://developer.apple.com/documentation/visionos/enabling-video-reflections-in-an-immersive-environment title: Enabling video reflections in an immersive environment description: Create a more immersive experience by adding video reflections in a custom environment. code_title: ContentView.swift code_sample: import SwiftUI

/// A view that presents the app's user interface. struct ContentView: View { @Environment(PlayerModel.self) private var player #if os(visionOS) @Environment(ImmersiveEnvironment.self) private var immersiveEnvironment #endif

var body: some View {
    #if os(visionOS)
    Group {
        switch player.presentation {
        case .fullWindow:
            PlayerView()
                .immersiveEnvironmentPicker {
                    ImmersiveEnvironmentPickerView()
                }
                .onAppear {
                    player.play()
                }
        default:
            // Shows the app's content library by default.
            DestinationTabs()
        }
    }
    .immersionManager()
    #else
    DestinationTabs()
        .presentVideoPlayer()
    #endif
}

}

#Preview(traits: .previewData) { ContentView() }

url: https://developer.apple.com/documentation/visionos/enabling-video-reflections-in-an-immersive-environment title: Enabling video reflections in an immersive environment description: Create a more immersive experience by adding video reflections in a custom environment. code_title: DestinationTabs.swift code_sample: import SwiftUI import SwiftData

/// The top level tab navigation for the app. struct DestinationTabs: View { /// Keep track of tab view customizations in app storage.

【19†code_samples.txt†file-l8kLlT5rccSnDGtLJLhCzrGO】

Spacer() Button("Enter immersive space") { Task { await openImmersiveSpace(id: immersiveSpace) appState.isImmersive = true } } } }

@MainActor var viewWhileImmersed: some View {
    VStack(spacing: 25) {
        Spacer()
        Text("Place spheres in your environment, and observe their colors change when you move between rooms.")
        HStack {
            Button("Add a sphere", systemImage: "circle", action: {
                appState.showPreviewSphere = true
            })
            
            Button("Remove all spheres", systemImage: "xmark.bin", action: {
                Task {
                    await appState.removeAllWorldAnchors()
                }
            })
        }
        visualizationPicker
        Button(appState.isWallSelectionLocked ? "Unlock the wall" : "Lock the wall") {
            if appState.readyToLockWall {
                appState.isWallSelectionLocked.toggle()
            } else {
                logger.info("Not ready to lock a wall.")
            }
        }.disabled(visualization != "Wall")

        Spacer()
        Button("Leave immersive space") {
            Task {
                await dismissImmersiveSpace()
                appState.isImmersive = false
            }
        }
    }
}

@MainActor var errorView: some View {
    var message: String
    switch appState.errorState {
    case .noError: message = "" // Empty string, since the app only shows this view in case of an error.
    case .providerNotAuthorized: message = "The app hasn't authorized one or more data providers."
    case .providerNotSupported: message = "This device doesn't support one or more data providers."
    case .sessionError(let error): message = "Running the ARKitSession failed with an error: \(error)."
    }
    return Text(message)
}

@MainActor var visualizationPicker: some View {
    HStack {
        Text("Room Visualization:")
        Picker("visualization", selection: $visualization) {
            ForEach(modes, id: \.self) {
                Text($0)
            }
        }
        .pickerStyle(.segmented)
        .frame(width: 400)
        .onChange(of: visualization) {
            Task {
                switch visualization {
                case "None":
                    appState.visualizationState = .none
                case "Occlusion":
                    appState.visualizationState = .occlusion
                case "Wall":
                    appState.visualizationState = .wall
                default:
                    return
                }
            }
        }
    }
}

}

#Preview(windowStyle: .automatic) { ContentView() }

url: https://developer.apple.com/documentation/arkit/arkit_in_visionos/building_local_experiences_with_room_tracking title: Building local experiences with room tracking description: Use room tracking in visionOS to provide custom interactions with physical spaces. code_title: Extensions.swift code_sample: import ARKit import RealityKit

extension SIMD4 { /// Retrieves first 3 elements var xyz: SIMD3 { self[SIMD3(0, 1, 2)] } }

extension ModelEntity { /// The geometry center of this model's faces. var centroid: SIMD3? { guard let vertices = self.model?.mesh.contents.models[0].parts[0].positions.elements else { return nil } guard let faces = self.model?.mesh.contents.models[0].parts[0].triangleIndices?.elements else { return nil }

    // Create a set of all vertices of the entity's faces.

Visible: 0% - 100%To "exit" an iOS or visionOS app, you can follow these general steps:

  1. Dismiss Immersive Space: If your app uses immersive spaces, ensure you dismiss them properly when needed.

  2. Monitor Scene Phase Changes: Use the @Environment(\.scenePhase) property to handle transitions such as when the app goes into the background.

Here are some code snippets to illustrate these concepts:

Dismissing Immersive Space

Use the dismissImmersiveSpace environment variable to exit from the immersive space. This is useful when your app needs to exit immersive mode due to user action or an error.

import SwiftUI

@main
struct MyApp: App {
    @Environment(\.dismissImmersiveSpace) private var dismissImmersiveSpace
    @Environment(\.scenePhase) private var scenePhase
    @State private var isImmersive = false

    var body: some Scene {
        WindowGroup {
            ContentView()
                .onChange(of: scenePhase) { newPhase in
                    if newPhase != .active && isImmersive {
                        Task {
                            await dismissImmersiveSpace()
                            isImmersive = false
                        }
                    }
                }
        }
    }
}

struct ContentView: View {
    @Environment(\.dismissImmersiveSpace) private var dismissImmersiveSpace
    @State private var isImmersive = false

    var body: some View {
        VStack {
            if isImmersive {
                Button("Exit Immersive Mode") {
                    Task {
                        await dismissImmersiveSpace()
                        isImmersive = false
                    }
                }
            } else {
                Button("Enter Immersive Mode") {
                    Task {
                        // Logic to enter immersive space
                        isImmersive = true
                    }
                }
            }
        }
    }
}

Handling Scene Phase Changes

Monitor the scene phase to perform actions like dismissing immersive spaces when the app is backgrounded.

struct ContentView: View {
    @Environment(\.scenePhase) private var scenePhase
    @Environment(\.dismissImmersiveSpace) private var dismissImmersiveSpace
    @State private var isImmersive = false

    var body: some View {
        VStack {
            // Your content
        }
        .onChange(of: scenePhase) { newPhase in
            if newPhase != .active && isImmersive {
                Task {
                    await dismissImmersiveSpace()
                    isImmersive = false
                }
            }
        }
    }
}

In these examples:

  • Dismiss Immersive Space: The dismissImmersiveSpace function is used to exit immersive mode.
  • Scene Phase Changes: The app monitors the scene phase to detect when it is no longer active and dismisses the immersive space accordingly.

For visionOS, you may also need to manage immersive spaces and handle transitions between different app states. Here's how you can incorporate such logic:

Dismissing Immersive Space in visionOS

@main
struct VisionApp: App {
    @Environment(\.dismissImmersiveSpace) private var dismissImmersiveSpace
    @Environment(\.scenePhase) private var scenePhase
    @State private var isImmersive = false

    var body: some Scene {
        WindowGroup {
            ContentView()
                .onChange(of: scenePhase) { newPhase in
                    if newPhase != .active && isImmersive {
                        Task {
                            await dismissImmersiveSpace()
                            isImmersive = false
                        }
                    }
                }
        }
        .onChange(of: isImmersive) { newValue in
            if !newValue {
                Task {
                    await dismissImmersiveSpace()
                }
            }
        }
    }
}

struct ContentView: View {
    @Environment(\.dismissImmersiveSpace) private var dismissImmersiveSpace
    @State private var isImmersive = false

    var body: some View {
        VStack {
            if isImmersive {
                Button("Exit Immersive Mode") {
                    Task {
                        await dismissImmersiveSpace()
                        isImmersive = false
                    }
                }
            } else {
                Button("Enter Immersive Mode") {
                    Task {
                        // Logic to enter immersive space
                        isImmersive = true
                    }
                }
            }
        }
    }
}

These code examples demonstrate how to manage app state transitions and ensure proper exit from immersive spaces on both iOS and visionOS. Always ensure that immersive spaces are dismissed appropriately to maintain a smooth user experience and adhere to best practices in app lifecycle management .I did that, but I can see from Xcode that the process is still running.In iOS and visionOS, the system controls the lifecycle of apps, including when they start and terminate. As developers, we generally don't have the ability to programmatically terminate our app from within the code. However, you can request the system to close the app or transition it to the background in specific scenarios. Here's a more comprehensive approach to handle this situation:

  1. Ensure Proper Cleanup: Ensure you are performing all necessary cleanup operations when transitioning to the background.

  2. Exit App (Not Recommended): While not recommended due to the potential for a poor user experience and rejection from the App Store, you can technically terminate an app using exit(0). However, use this only for debugging purposes.

Best Practices for Exiting the App

Instead of forcing an app exit, follow these best practices:

  • Handle Background Transitions: Ensure your app saves state and releases resources appropriately when entering the background.

  • Use Notifications: Use notifications to inform the system of significant events or changes that might require the app to be closed.

Handling Background Transitions

Ensure your app handles state transitions properly:

import SwiftUI

@main
struct MyApp: App {
    @Environment(\.scenePhase) private var scenePhase
    @StateObject private var appState = AppState()

    var body: some Scene {
        WindowGroup {
            ContentView()
                .environmentObject(appState)
                .onChange(of: scenePhase) { newPhase in
                    handleScenePhaseChange(newPhase)
                }
        }
    }

    private func handleScenePhaseChange(_ newPhase: ScenePhase) {
        switch newPhase {
        case .background:
            // Perform any background tasks or cleanup here
            appState.cleanup()
        case .inactive:
            // Handle transition to inactive state
            appState.saveState()
        case .active:
            // Handle app becoming active again
            appState.restoreState()
        @unknown default:
            break
        }
    }
}

class AppState: ObservableObject {
    // Properties and methods to manage app state
    func cleanup() {
        // Perform cleanup
    }

    func saveState() {
        // Save current state
    }

    func restoreState() {
        // Restore saved state
    }
}

Using Notifications

Use notifications to inform the system about specific events:

NotificationCenter.default.post(name: UIApplication.didEnterBackgroundNotification, object: nil)

Force Exit (Not Recommended for Production)

For debugging purposes, you can use:

import UIKit

func exitApp() {
    exit(0)
}

Example of Proper State Management

import SwiftUI

@main
struct MyApp: App {
    @Environment(\.scenePhase) private var scenePhase
    @StateObject private var appState = AppState()

    var body: some Scene {
        WindowGroup {
            ContentView()
                .environmentObject(appState)
                .onChange(of: scenePhase) { newPhase in
                    if newPhase == .background {
                        appState.cleanup()
                        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                            exit(0)
                        }
                    }
                }
        }
    }
}

class AppState: ObservableObject {
    func cleanup() {
        // Perform cleanup tasks
    }
}

Important Note

Using exit(0) should be avoided in production apps as it can lead to a poor user experience and rejection during the App Store review process. Always strive to manage app state transitions smoothly and let the system handle the app lifecycle.

Handling App Exit created at Tue Jan 20 1970 21:26:59 GMT+0000 (Coordinated Universal Time)

Related Chats

Handling App Exit 0.999

MultipeerManager Error Fix 0.925

Reusable SwiftUI custom view. 0.918

SwiftUI RealityKit Integration 0.911

Preload Assets in visionOS 0.898

Immersive View Phases 0.885

Animate Using withAnimation 0.840

Switch to guard statement 0.837

Shared ViewModel Across Views 0.807

Calculate pointC using SIMD3 0.792