Find Sub-Component Cylinder

TODO: collapasable, copyable, download, etc

I have ```

if let lightsaber = try? await Entity(named: "Scene", in: realityKitContentBundle) { if let cylinder = lightsaber.entities.first?.findEntity(named: "Cylinder") {


But lightsaber is an Entity and doesn't have the entities property. How can I find a sub-component named Cylinder?
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<Value> {
    var value: Value
    subscript<T>(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.
To find a sub-component named "Cylinder" within an `Entity` in RealityKit, you can use the `Entity` method `findEntity(named:)`. Here's an example of how you can modify your code to achieve this:

```swift
if let lightsaber = try? await Entity(named: "Scene", in: realityKitContentBundle) {
    if let cylinder = lightsaber.findEntity(named: "Cylinder") {
        // Your code to work with the cylinder entity
    }
}

In this modified code, findEntity(named:) is used on lightsaber directly to find the sub-component named "Cylinder". This method recursively searches for an entity with the specified name within the hierarchy of the lightsaber entity.I have this code func handleCollision(enemyEntity: Entity, lightSaber: Entity, content: RealityViewContent) { try? await Task.sleep(for: .milliseconds(500)) print("removing enemyEntity") content.remove(enemyEntity) ...

I don't see the enemy removed from the scene, they are still present. What could be going wrong?There could be several reasons why the enemyEntity is not being removed from the scene. Here are some potential issues and solutions:

  1. Task.sleep not Awaited: Ensure the sleep task is correctly awaited. If not, it might not delay as expected. Your use of try? await Task.sleep(for: .milliseconds(500)) seems correct, but double-check that this line is not being skipped or causing issues.

  2. Entity Hierarchy: Make sure enemyEntity is correctly referenced within the hierarchy of content. If enemyEntity is not a direct child of content, the removal might not work as intended.

  3. Threading Issues: Ensure that the removal of the entity is happening on the main thread, as UI updates (including RealityKit scene updates) need to occur on the main thread.

  4. Proper Method for Removal: Verify that the remove method on content works as intended. Sometimes, different methods or approaches might be required to remove an entity from the scene.

Here’s a revised version of your code with some additional checks and ensuring the operation runs on the main thread:

func handleCollision(enemyEntity: Entity, lightSaber: Entity, content: RealityViewContent) {
    Task {
        // Ensure delay is properly awaited
        try? await Task.sleep(for: .milliseconds(500))
        print("removing enemyEntity")
        
        // Perform UI update on the main thread
        await MainActor.run {
            if let enemy = content.findEntity(named: enemyEntity.name) {
                content.remove(enemy)
                print("enemyEntity removed")
            } else {
                print("enemyEntity not found in content")
            }
        }
    }
}

Key Changes:

  • Using Task to encapsulate the async operation: This ensures that the sleep is properly awaited within an async context.
  • Running the removal on the main thread using MainActor.run: This ensures that UI-related updates are performed on the main thread.
  • Adding a check to verify if enemyEntity is correctly referenced within content before removal: This ensures that you are removing the correct entity.

Make sure content.findEntity(named:) matches the correct entity name. Adjust the method if your RealityKit scene structure differs. is not a direct child of content, the removal might not work as intended. - how would I remove it no matter where it was in the heirarchy?To remove an entity regardless of where it is in the hierarchy, you can use the findEntity(named:) method on the top-level content entity. This method recursively searches the entire entity hierarchy for an entity with the specified name. Once found, you can remove it from its parent.

Here’s an updated version of your code:

func handleCollision(enemyEntity: Entity, lightSaber: Entity, content: RealityViewContent) {
    Task {
        // Ensure delay is properly awaited
        try? await Task.sleep(for: .milliseconds(500))
        print("removing enemyEntity")
        
        // Perform UI update on the main thread
        await MainActor.run {
            if let enemy = content.findEntity(named: enemyEntity.name) {
                enemy.removeFromParent()
                print("enemyEntity removed")
            } else {
                print("enemyEntity not found in content")
            }
        }
    }
}

Explanation:

  • Using findEntity(named:) on content: This recursively searches for the enemyEntity by name throughout the entire hierarchy.
  • Using removeFromParent(): This method removes the entity from its parent, which effectively removes it from the scene.

Make sure the enemyEntity has a unique name in the scene to avoid conflicts when using findEntity(named:). If the entity names are not unique, you may need to implement additional logic to ensure you are removing the correct entity.Can I find by id?Yes, you can find an entity by its unique identifier (UUID) in RealityKit. Each Entity has a id property which you can use to uniquely identify it. To remove an entity by its UUID, you can traverse the hierarchy and match the id property.

Here’s an example of how you can find and remove an entity by its UUID:

func handleCollision(enemyEntity: Entity, lightSaber: Entity, content: RealityViewContent) {
    Task {
        // Ensure delay is properly awaited
        try? await Task.sleep(for: .milliseconds(500))
        print("removing enemyEntity")
        
        // Perform UI update on the main thread
        await MainActor.run {
            if let enemy = findEntity(by: enemyEntity.id, in: content) {
                enemy.removeFromParent()
                print("enemyEntity removed")
            } else {
                print("enemyEntity not found in content")
            }
        }
    }
}

// Recursive function to find an entity by its id
func findEntity(by id: UUID, in entity: Entity) -> Entity? {
    if entity.id == id {
        return entity
    }
    for child in entity.children {
        if let found = findEntity(by: id, in: child) {
            return found
        }
    }
    return nil
}

Explanation:

  • Task for Async Context: The Task ensures the asynchronous context for the delay and UI updates.
  • MainActor.run: Ensures that the entity removal happens on the main thread.
  • Recursive Search Function (findEntity(by:id:)): This function recursively traverses the entity hierarchy to find the entity with the specified UUID.
  • Removing the Entity: Once found, removeFromParent() is called to remove the entity from its parent.

This method ensures that the entity is found and removed regardless of its position in the hierarchy.Cannot convert value of type 'RealityViewContent' to expected argument type 'Entity' Cannot convert value of type 'UInt64' to expected argument type 'UUID'The error messages indicate a type mismatch. RealityViewContent needs to be converted to Entity, and UInt64 to UUID. However, it's important to note that RealityKit Entity does not use UUID directly for its ID but instead uses UInt64.

Here's how you can adjust your code to find and remove an entity using its UInt64 ID:

  1. Ensure the enemyEntity is correctly identified.
  2. Traverse the hierarchy to find the entity by its UInt64 ID.
  3. Remove the entity if found.

Here’s the adjusted code:

func handleCollision(enemyEntity: Entity, lightSaber: Entity, content: Entity) {
    Task {
        // Ensure delay is properly awaited
        try? await Task.sleep(for: .milliseconds(500))
        print("removing enemyEntity")
        
        // Perform UI update on the main thread
        await MainActor.run {
            if let enemy = findEntity(by: enemyEntity.id, in: content) {
                enemy.removeFromParent()
                print("enemyEntity removed")
            } else {
                print("enemyEntity not found in content")
            }
        }
    }
}

// Recursive function to find an entity by its id
func findEntity(by id: UInt64, in entity: Entity) -> Entity? {
    if entity.id == id {
        return entity
    }
    for child in entity.children {
        if let found = findEntity(by: id, in: child) {
            return found
        }
    }
    return nil
}

Explanation:

  • Parameter Types: Ensure content is of type Entity instead of RealityViewContent.
  • Recursive Search: The findEntity(by:in:) function recursively searches through the hierarchy of entities to find the one with the matching UInt64 ID.
  • Entity ID: Uses the UInt64 ID of the entity to identify it.

This should resolve the type mismatch issues and allow you to correctly find and remove the entity by its ID.How can. Iiterate through content.entitiesTo iterate through content.entities, you need to ensure that content is a type that has an entities property or collection. Assuming content is an Entity or has a similar structure, you can access and iterate through its children.

Here's an example demonstrating how to iterate through content.entities:

func handleCollision(enemyEntity: Entity, lightSaber: Entity, content: Entity) {
    Task {
        // Ensure delay is properly awaited
        try? await Task.sleep(for: .milliseconds(500))
        print("removing enemyEntity")
        
        // Perform UI update on the main thread
        await MainActor.run {
            if let enemy = findEntity(by: enemyEntity.id, in: content) {
                enemy.removeFromParent()
                print("enemyEntity removed")
            } else {
                print("enemyEntity not found in content")
            }
        }
    }
}

// Recursive function to find an entity by its id
func findEntity(by id: UInt64, in entity: Entity) -> Entity? {
    if entity.id == id {
        return entity
    }
    for child in entity.children {
        if let found = findEntity(by: id, in: child) {
            return found
        }
    }
    return nil
}

// Example function to iterate through all entities in content
func iterateEntities(in content: Entity) {
    for entity in content.children {
        print("Entity found: \(entity)")
        // If needed, you can also iterate through each child's children
        for child in entity.children {
            print("Child entity found: \(child)")
        }
    }
}

Explanation:

  • handleCollision: This function handles the collision and attempts to remove the enemy entity after a delay.
  • findEntity(by:in:): This recursive function searches for an entity with the given UInt64 ID within the hierarchy.
  • iterateEntities(in:): This function demonstrates how to iterate through the entities within content and print them out.

In this example:

  • content.children is used to iterate over the direct children of the content entity.
  • If you need to further iterate through the hierarchy, you can add nested loops or recursion as shown in the findEntity(by:in:) function.

Ensure that the content parameter in your functions is an Entity or a compatible type that has a children collection for this to work correctly.

Find Sub-Component Cylinder created at Tue Jan 20 1970 21:25:25 GMT+0000 (Coordinated Universal Time)

Related Chats

Find Sub-Component Cylinder 0.999

Preload Assets in visionOS 0.669

MultipeerManager Error Fix 0.668

Reusable SwiftUI custom view. 0.664

SwiftUI RealityKit Integration 0.647

Immersive View Phases 0.639

Animate Using withAnimation 0.639

Switch to guard statement 0.639

Handling App Exit 0.636

Shared ViewModel Across Views 0.631