SoFunction
Updated on 2025-03-02

Detailed explanation of basic data types of Swift tutorials

Basic Type

Although Swift is a brand new programming language designed for the development of iOS and OS X apps, many of Swift's features are still similar to C and Objective-C.

Swift also provides basic data types similar to C and Objective-C, including shaping Int, floating-point numbers Double and Float, boolean type Bool, and string type String. Swift also provides two more powerful basic collection data types, Array and Dictionary. For more detailed content, please refer to: Collection Types.

Like C, Swift uses specific names to define and use variables. Similarly, constants can be defined in Swift. Unlike C, constants in Swift are more powerful, and using constants during programming can make the code look safer and more concise.

In addition to common data types, Swift also integrates "tuple" types not available in Objective-C and can be passed as a whole. Tuples can also be returned by a function, allowing the function to return multiple values ​​at once.

Swift also provides optional types to handle unknown values ​​that do not exist. The optional type means: this value either exists, and is equal to x, or does not exist at all. Optional types are similar to the nil value of a pointer in Objective-C, but nil is only useful for classes, while Optional types are available for all types and are safer. Optional types are at the heart of most new Swift features.

Optional types are just an example of Swift as a type-safe programming language. Swift can help you discover type errors in encoding faster. If your code expects the parameter type to be passed is String, then type safety will prevent you from passing an Int value incorrectly. This allows programmers to discover and fix problems faster during the development period.

Constants and variables

Constants and variables are represented by a specific name, such as maximumNumberOfLoginAttempt or welcomeMessage. A constant points to a value of a specific type, such as the number 10 or the character "hello". The value of a variable can be continuously modified as needed, while the value of a constant cannot be modified quadratically.

Declaration of constants and variables

Constants and variables need to be declared before use. In Swift, use the let keyword to declare a constant, and the var keyword to declare a variable. As shown in the following example:

Copy the codeThe code is as follows:

let maximumNumberOfLoginAttempts = 10
var currentLoginAttempt = 0

The above code can be understood as:

Declare a constant with a value of 10 called maximumNumberOfLoginAttempts. Then declare a variable currentLoginAttempt to initially have 0.

In this example, the maximum number of login attempts 10 is unchanged and is therefore declared as a constant. The number of attempts that have been logged in is variable and is therefore defined as a variable. You can also declare multiple variables or constants in a line, separated by a number:

Copy the codeThe code is as follows:

var x = 0.0, y = 0.0, z = 0.0

Note: If a value does not change in the subsequent code, it should be declared as a constant using the let keyword. Variables are only used to store the values ​​that will be changed.

Type annotation

When declaring constants and variables, you can use annotations to indicate the type of the variable or constant. Use the : sign plus space plus type name to complete type annotation after the variable or constant name. The following example is to declare a variable called welcomeMessage, and the annotation type is a string String:

var welcomeMessage: String
The semicolon ":" works here as saying: ...is of type, so the above code can be understood as:

Declare a variable called welcomeMessage, its type is String

This type annotation indicates that the welcomeMessage variable can store any string type values ​​without error, such as welcomeMessage = "hello"

Note: In actual programming, type annotations are rarely needed. When defining constants or variables, Swift has determined the type information based on the initialized value. Swift can almost implicitly determine the types of variables or constants, see:Type Safety and Type Inference. In the above welcomeMessage example, the initialization value is not given, so a better way is to specify the type of the welcomeMessage variable instead of letting Swift implicitly deduce the type.

Naming of constants and variables

Almost any character can be used as constant and variable names in Swift, including Unicode, for example:

Copy the codeThe code is as follows:

let π = 3.14159
let Hello = "Hello world"
let = "dogcow"

However, the name cannot contain mathematical symbols, arrows, invalid Unicode, horizontal lines and tabs, and cannot start with numbers, although numbers can be included in the name. Once the declaration is completed, you cannot declare a variable or constant with the same name again, or change its type. Variables and constants are also not interchangeable.

Note: If you want to name a constant or variable with Swift reserved words, you can use the ` symbol to enclose the naming. Nevertheless, try not to use reserved words as variable/constant names unless in particular intention.

You can change the value of a variable to other values ​​of the type it declares. In the following example, the value of the variable friendlyWelcome is modified from "Hello!" to "Bonjour!":

Copy the codeThe code is as follows:

var friendlyWelcome = “hello!”
friendlyWelcome = “Bonjour!”
// friendlyWelcome is now “Bonjour!”

Unlike variables, the value of a constant cannot be modified once it is determined. If you want to try to change the value of a constant, you will report an error when compiling the code.

Copy the codeThe code is as follows:

let languageName = "Swift"
languageName = "Swift++"
// this is a compile-time error - languageName cannot be changed

Output constants and variables

Swift uses println to output variables or constants:

Copy the codeThe code is as follows:

println(friendlyWelcome)
// prints “Bonjour!”

println is a global function that outputs a value and finally outputs a newline. In Xcode, println output is in the console. The print function is similar, except that the line break will not be output in the end.

println function usually outputs a string

Copy the codeThe code is as follows:

println("This is a string")
// prints "This is a string"

The println function can also format and output some log information, just like the behavior of the NSLog function in Cocoa, which can include some constants and variables themselves. Swift inserts variable name as placeholder in the string, and uses backslash() to prompt Swift to replace the variable/constant name as its actual value, such as:
Copy the codeThe code is as follows:

println(“The current value of friendlyWelcome is (friendlyWelcome)”) // prints “The current value of friendlyWelcome is Bonjour!”

Note: See the details for formatting charactersString Interpolation

Comments

Statements that do not participate in compilation are called comments, and comments can prompt you with the intention of the code. The comments in Swift are the same as those in C, with single-line comments

Copy the codeThe code is as follows:

//this is a comment

and multi-line comments, separated by / and /
Copy the codeThe code is as follows:

/* this is also a comment,
but written over multiple lines */

Unlike C, multi-line comments can be nested. You need to start a multi-line comment first, then start a second multi-line comment, and close the second one, and then the first one when closing the comment. as follows
Copy the codeThe code is as follows:

/* 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 */

This allows you to continue adding comments to large comments in the commented code blocks

semicolon

Unlike some other programming languages, Swift does not need to use semicolons; to separate each statement. Of course you can also choose to use a semicolon, or you want to write multiple statements in one line.

Copy the codeThe code is as follows:

let cat = ""; println(cat)
// prints ""

Integer

Integers are numbers like 42 and -23 without fractions, including signed (positive, negative, 0) and unsigned (positive, 0). Swift provides 8, 16, 32 and 64-bit numeric forms. Similar to C, you can use the 8-bit unsigned integer UInt8 or the 32-bit integer Int32. Like other Swift types, these type names have capitalized initials.

Integer boundaries

Use min or max values ​​to get the maximum and minimum values ​​of this type, such as:

Copy the codeThe code is as follows:

let minValue = // minValue is equal to 0, and is of type UInt8
let maxValue = // maxValue is equal to 255, and is of type UInt8

These value boundary values ​​distinguish the types of integers (such as UInt8), so they can be used in expressions like other values ​​of that type without considering the benefits.

Int Type

Generally speaking, programmers do not need to select the number of integer bits when writing code. Swift provides an additional integer type Int, which is an integer number of digits with the same word length as the current machine environment.

1. On a 32-bit machine, Int is the same size as Int32
2. On a 64-bit machine, Int is the same size as Int64

Unless you really need to use a positive number of a specific word length, try to use the Int type. This ensures the portability of the code. Even on 32-bit platforms, Int can store values ​​in the range of -2,147,483,648 to 2,147,483,647, which is enough for most positive numbers.

UInt Type

Swift also provides an unsigned UInt, which is also equivalent to the word appearance of the current machine environment.

1. On a 32-bit machine, UInt is the same size as UInt32
2. On a 64-bit machine, Int is the same size as Int64

Note: UInt is only required to use UInt when explicitly specifying an unsigned number with an equal length to the machine word. In other cases, try to use Int, even if this variable is determined to be unsigned. All use Int to ensure the portability of the code and avoid conversion between different numeric types. See detailsType Safety and Type Inference

5. Floating point number

Floating points are numbers with fractions like 3.14159, 0.1, -273.15. Floating points can express values ​​that are wider (larger or smaller) than Int. Swift supports two signed floating point types:

Type can represent signed floating point numbers of 64 bits. When the table number is required to be very large or the accuracy requirements are very high, you can use the Double type.
Type can represent signed floating point numbers of 32. The Float type can be used when the number you want to express does not require 64-bit precision.

Note Double has at least 15 decimal places, and Float has at least 6 decimal places. The appropriate number of floating point decimal places depends on the range of floating point numbers you need to process in your code.

6. Type safety and type deduction

Swift is a type-safe language. Type safety means that you need to figure out the types of variables when programming. If your code part requires a string, you cannot pass an integer type incorrectly.

Because Swift is type-safe, it will check your code when it is compiled, and an error will be reported when any type does not match. This allows programmers to catch and fix errors as quickly as possible during development.

Type checking can help avoid errors when using different types of values. However, this does not mean that you have to specify the type declared by each constant and variable. If you do not specify the type you need, Swift uses type derivation to specify the corresponding type. Type derivation enables the compiler to automatically deduce the type of a specific expression through the initialization value you provide during compilation.

Type derivation makes Swift require fewer type declaration statements than C or Objective-C. Constants and variables are still explicitly typed, but most of the work that specifies their type is done for you.

Type derivation is particularly useful when you declare a constant or variable and give the initial value type. This is usually done by assigning constant values ​​to declared constants or variables. (Constant values ​​are values ​​that appear directly in the source code, such as Examples 42 and 3.14159 below.)

For example, if you specify 42 to a new constant variable, without saying what type it is, Swift infers that the constant you want is an integer because you have initialized it as an integer

Copy the codeThe code is as follows:

let meaningOfLife= 42
// meaningOfLife is inferred to be of typeInt

Similarly, if you do not specify the type of floating point value, Swift infers that you want to create a Double:
Copy the codeThe code is as follows:

let pi = 3.14159
// pi is inferred to be of type Double

Swift always chooses Double (not Float) when it requires a floating point number type. If you add integers and floating-point numbers in an expression, you will deduce a Double type:
Copy the codeThe code is as follows:

let anotherPi= 3 + 0.14159
// anotherPi is also inferred to be of typeDouble

The constant value 3 does not show the specified type, so Swift deduces the output type Double based on the floating point value in the expression.

Numerical expression

Integer constants can be written as:

1. A decimal number without prefix
2. A binary number, prefixed by 0b
3. An octal number prefixed with 0o
4. A hexadecimal number prefixed with 0x

All of the following integer constants can be used to express decimal value 17:

Copy the codeThe code is as follows:

let decimalInteger= 17
let binaryInteger = 0b10001 // 17 in binary notation
let octalInteger = 0o21 // 17 in octal notation
let hexadecimalInteger = 0x11 // 17 inhexadecimal notation

Floating points can be decimal (without prefix) or hexadecimal (prefixed with 0x), and there must always be a decimal number (or hexadecimal number) on both sides of the decimal point. They can also have an optional exponent, represented by a capital or lowercase e for decimal floating point, or uppercase/lowercase p for hexadecimal floating point

A decimal number with an exponential exp, the actual value is equal to the power of exp by the cardinality multiplied by 10, such as:

◎1.25e2 means 1.25×102, or 125.0.
◎1.25e-2 means 1.25×10-2, or 0.0125.

Hexadecimal number with exponential exp, the actual value is equal to the power of exp by multiplying the base number by 2, such as:

◎0xFp2 means 15×22, or 60.0.
◎0xFp-2 means 15×2-2, or 3.75.

All of the following floating point constants represent decimal 12.1875:

Copy the codeThe code is as follows:

let decimalDouble= 12.1875
let exponentDouble= 1.21875e1
let hexadecimalDouble= 0xC.3p0

Numerical type conversion

Use the Int type for all common numeric integer constants and variables in the code, even if they are known to be non-negative. This means that the numeric constants and variables in the code are compatible with each other and can match the automatically derived types.

These numeric types should be used only if some reason (performance, memory usage, or other necessary optimizations) do require other numeric types. Using explicitly specifying the type of length in these cases helps to find value range overflows, while documentation should be left behind.

Integer conversion

Can be stored in an integer constant or range of variables that are different depending on each numerical type. An Int8 constant or variable can store numbers between range -128 and 127, while a UInt8 constant or variable can store numbers between 0 and 255. An incorrect assignment will cause the compiler to report an error:

Copy the codeThe code is as follows:

let cannotBeNegative: UInt8 = -1
// UInt8 cannot store negative numbers, and so this will report an error
let tooBig: Int8 = + 1
// Int8 cannot store a number larger thanits maximum value,
// and so this will also report an error

Because each numeric type can store different ranges of values, you must gradually convert it on the underlying numeric type. This prevents hidden conversion errors and helps clarify the intent of type conversions in your code.

To convert a specific numeric type to another, you need to define a new variable of the desired type and initialize it with the current value. In the following example, the constant twoThousand is of type UInt16, while the constant one is of type UINT8. They cannot be added directly because of different types. Instead, the example calls UInt16(one) to create a new variable of type UInt16 initialized with the value of the variable one, and uses this value to replace the original value to participate in the operation:

Copy the codeThe code is as follows:

let twoThousand: UInt16 = 2_000
let one: UInt8 = 1
let twoThousandAndOne= twoThousand + UInt16(one)

It can be done because the types of both the addition parties are UInt16, you can now do addition. The output constant (twoThousandAndOne) is inferred to be of type UInt16, because it is the sum of the values ​​of two UInt16.

SomeType(ofInitialValue) is Swift's default type conversion method. In terms of implementation, UInt16 has a constructor that accepts UINT8 values, which is used to construct a new UInt16 variable from the existing UInt8. You cannot pass in any type of parameter, it must be a type that can be accepted by UInt16 initialization. How to extend an existing type and specify that new types are accepted (including your own type definition) can be found inExtensions

Integer and floating point conversion

The conversion between integer and floating point types must be explicitly declared:

Copy the codeThe code is as follows:

let three = 3
let pointOneFourOneFiveNine= 0.14159
let pi = Double(three) +pointOneFourOneFiveNine
// pi equals 3.14159, and is inferred to beof typde Double

Here, the value of the constant three is used to create a new variable of type Double so that the expression is the same type on both sides. Without this conversion, the addition operation will not be allowed. Vice versa, an integer type can be initialized with a double or float value:
Copy the codeThe code is as follows:

let integerPi= Int(pi)
// integerPi equals 3, and is inferred tobe of type Int

When a new integer value is initialized in this way, the floating point value is always truncated. This means that 4.75 becomes 4, and -3.9 becomes -3.

Note: The type conversion rules for numeric type constants/variables are different from the conversion rules for numeric type constants. The constant value 3 can be added directly to the constant value 0.14159, because the constant value does not have a clear type. Their types are derived by the compiler.

Type alias

A type alias is an alternative name for an existing type definition. You can use the typealias keyword to define type alias. Type alias can help you use a more context-sensitive name to refer to an existing type, such as when dealing with an external type of type with a specified length:

Copy the codeThe code is as follows:

typealias AudioSample = UInt16

Once you have defined a type alias, you can use the alias wherever you might use the original name:
Copy the codeThe code is as follows:

var maxAmplitudeFound=
// maxAmplitudeFound is now 0

Here, AudioSample is defined as a UInt16 alias. Because it is an alias, the call is actually a call, thus assigning the initial value 0 to the maxAmplitudeFound variable.

Boolean type

Boolean types in Swift are defined using Bool, also known as Logical (logical) types, with optional values ​​being true and false:

Copy the codeThe code is as follows:

let orangesAreOrange = true
let turnipsAreDelicious = false

Here the types of orangesAreOrange and turnipsAreDelicious are derived as Bool because they are initialized to be constant values ​​of the Bool type. Like Int and Double types, when defining Boolean types, you do not need to explicitly give the data type, you only need to directly assign the value to true or false. Type derivation makes Swift code more precise and readable when initializing a constant/variable with a constant of a certain type. Boolean types are particularly suitable in conditional statements, such as in if statements
Copy the codeThe code is as follows:

if turnipsAreDelicious {
println("Mmm, tasty turnips!")
} else {
println("Eww, turnips are horrible.")
}
// prints "Eww, turnips are horrible."

Conditional statements like if statements, we will follow the chaptersControlFlowThere is a detailed introduction. Swift's type-safe policy prevents other non-boolean types from being converted to boolean types, such as

Copy the codeThe code is as follows:

let i = 1
if i {
// this example will not compile, and will report an error
}

An error will be reported, but this is feasible in other programming languages. But the following definition is correct:
Copy the codeThe code is as follows:

let i = 1
if i == 1 {
// this example will compile successfully
}

The result of i == 1 is a boolean type, so it can pass type checking. Comparisons like i==1 will be discussed in the chapter [Basic Operators]. The above example is also an example of Swift type safety. Type safety avoids accidental type errors and ensures that the intent of the code is clear.

Tuple Type

Tuple types can assemble some different data types into one element, which can be of any type and do not need to be of the same type.

In the following example, (404, "Not Found") is an HTTP status code. HTTP status code is a specific status code returned when requesting a web page. The specific meaning of the 404 error is that the page is not found.

Copy the codeThe code is as follows:

let http404Error = (404, “Not Found”) // http404Error is of type (Int, String), and equals (404, “Not Found”)

This tuple consists of an Int and a String String. This combination contains numbers and also contains string descriptions that are easy to understand. This tuple can be described as a tuple of type (Int, String).

Programmers can create tuple types they need at will, such as (Int, Int), or (String, Bool), etc. At the same time, the number of types that make up tuples is also unlimited. The values ​​of a tuple can be accessed separately in the following ways:

Copy the codeThe code is as follows:

let (statusCode, statusMessage) = http404Error
println("The status code is \(statusCode)")
// prints "The status code is 404"
println("The status message is \(statusMessage)")
// prints "The status message is Not Found"

If only individual values ​​in the tuple are needed, you can use (_) to ignore unwanted values
Copy the codeThe code is as follows:

let (justTheStatusCode, _) = http404Error
println("The status code is \(justTheStatusCode)")
// prints "The status code is 404"

In addition, you can also use the element sequence number to select the value in the tuple, note that the sequence number starts from 0
Copy the codeThe code is as follows:

println("The status code is \(http404Error.0)")
// prints "The status code is 404"
println("The status message is \(http404Error.1)")
// prints "The status message is Not Found"

When creating a tuple, you can also directly specify the name of each element, and then directly access it using the tuple name. Element name, such as:
Copy the codeThe code is as follows:

let http200Status = (statusCode: 200, description: "OK")
println("The status code is \()")
// prints "The status code is 200"
println("The status message is \()")
// prints "The status message is OK"

Tuple types are particularly suitable when returning values ​​as functions, and can return more information needed by users for functions. For example, a function that requests a web page can return a tuple of type (Int, String) to represent the success or failure of the page acquisition. Returning two tuples composed of different types can provide more return information than returning only one value of one type. See detailsFunctions with Multiple Return Values

Optional type

An optional type can be used when a value may not exist. The definition of this type is: either this value exists and is equal to x, or it does not exist in this value.

Note: This type does not exist in C and Objective-C, but there is a similar type in Objective-C called nil, but it is only useful for objects. For other cases, the Object-C method returns a special value (such as NSNotFound) to indicate that the value does not exist. This way assumes that the method caller knows the existence and meaning of this special value. Swift's optional types help you define situations where any value does not exist.

Here is an example. In Swift, there is a method called toInt, which can convert a string to an Int type. But it should be noted that not all strings can be converted to integers. For example, the string "123" can be converted to 123, but "hello, world" cannot be converted.

Copy the codeThe code is as follows:

let possibleNumber = "123"
let convertedNumber = ()
// convertedNumber is inferred to be of type "Int?", or "optional Int"

Since the toInt method may fail, it returns an optional Int type, unlike the Int type. An optional Int type is marked Int?, not Int. The question mark indicates that its value is optional, it may be an Int, or the returned value does not exist.

If statement and forced unpackage

Programmers can use an if statement to detect whether an optional type contains a specific value. If an optional type does contain a value, it will return true in the if statement, otherwise it will return false. If you have detected and confirmed that the value exists, you can use or output it. When outputting, you only need to add an exclamation mark (!) to the name, which means telling the compiler: I have detected this value and can use it. like:

Copy the codeThe code is as follows:

if convertedNumber {
println("\(possibleNumber) has an integer value of \(convertedNumber!)")
} else {
println("\(possibleNumber) could not be converted to an integer")
}
// prints "123 has an integer value of 123"


We will introduce conditional statements like if statements in detail in the following chapter ControlFlow.

Select Binding

Selecting binding helps determine whether an optional value contains a value. If included, convert the value into a temporary constant or variable. Selection binding can be used in if or while statements to check if there are values ​​outside the optional type and extract possible values. If and while statements are detailed in ControlFlow.

The method is as follows:

Copy the codeThe code is as follows:

if let constantName = someOptional {
statements
}

Then the previous example can also be rewritten as:
Copy the codeThe code is as follows:

if let actualNumber = () {
println("\(possibleNumber) has an integer value of \(actualNumber)")
} else {
println("\(possibleNumber) could not be converted to an integer")
}
// prints "123 has an integer value of 123"

The above code is not difficult to understand: if the optional Int type returned contains a value, then define a constant actualNumber to equal this value and use it directly in subsequent code.

If the conversion is successful, the actualNumber constant is available on the first branch of the if and is initialized to the value contained by the optional type, and does not need to be used! Prefix. In this example, actualNumber is simply used to print the results.

Both constants and variables can be used for optional binding. If you want to modify the value of actualNumber in the first branch of if, you can write it as if var actualNumber, and actualNumber becomes a variable so that it can be modified.

nil

You can specify a special value nil to the optional type:

Copy the codeThe code is as follows:

var serverResponseCode: Int? = 404
// serverResponseCode contains an actual Int value of 404
serverResponseCode = nil
// serverResponseCode now contains no value

If you define an optional type and do not give an initial value, it will default to nil
Copy the codeThe code is as follows:

var surveyAnswer: String? // surveyAnswer is automatically set to nil

Note: Swift's nil is different from nil in Object-C. In Object-C, nil is a pointer to an object that does not exist. In Swift, nil is not a pointer but a specific type of null value. Any type of optional variable can be set to nil, not just a pointer.

Implicit unpacking optional types

In the example above, the optional type indicates that a constant/variable may have no value. The optional type can be detected by the if statement whether there is a value and can be unpacked by the optional binding.

However, in some cases, optional types are always valid, so type checking can be implicitly removed by definition and the optional types are forced to be used. These optional types are become optional types that are implicitly unpacked. You can add it directly after the type! Instead? To specify.

The optional types of implicit unpacking are mainly used when a variable/constant value will exist after the definition is completed instantly. This is mainly used in the initialization process of the class. See moreUnowned References and Implicitly Unwrapped Optional Properties

The optional types of implicit unpacking are essentially optional types, but can be used as general types without verifying whether the value exists every time. The following example shows the difference between optional types and unpacking optional types.

Copy the codeThe code is as follows:

let possibleString: String? = "An optional string."
println(possibleString!) // requires an exclamation mark to access its value
// prints "An optional string."

let assumedString: String! = "An implicitly unwrapped optional string."
println(assumedString) // no exclamation mark is needed to access its value
// prints "An implicitly unwrapped optional string."

You can use the implicit unpacking optional types as optional types that are automatically unpacked each time you use them. That is, it is not added after variables/constants every time they are used! Instead, add it directly when defining.

Note: If an implicitly unpacked optional type does not contain an actual value, access to it will throw a runtime error. Add after the variable/constant name! The same is true.

You can still use the unpacking optional type as a normal optional type to detect whether there is a value.

Copy the codeThe code is as follows:

if assumedString {
println(assumedString)
}
// prints "An implicitly unwrapped optional string."
Or check by selecting binding

if let definiteString = assumedString {
println(definiteString)
}
// prints "An implicitly unwrapped optional string."


Note: If there is no value for an optional type, you should not use unpacked optional types. In this case, you must use the normal optional type.

assertion

Optional types allow programmers to detect whether a value exists during runtime and then use code to handle non-existence situations. However, in some cases, if a value does not exist or the value does not meet the conditions, it will directly affect the execution of the code. At this time, assertions are needed. In this case, assertion ends the execution of the program and provides a basis for debugging.

Debugging with assertions

Assertion is a way to detect whether a condition is true in real time, that is, assertion assumes that the condition is true. Assertions ensure that subsequent code execution depends on the conditionality. If the condition is met, the code continues to execute, and if this condition is false, the code will interrupt execution.

In Xcode, if it is interrupted during debugging, you can view the program status when the assertion fails by viewing the debug statement. Assertions can also provide appropriate debug information. Use the global function assert to debug using assert. The assert function accepts a Boolean expression and a message displayed when the assert fails, such as:

Copy the codeThe code is as follows:

let age = -3
assert(age >= 0, "A person's age cannot be less than zero")
// this causes the assertion to trigger, because age is not >= 0

When a current condition returns false, the subsequent error log will be output.

In this example, only when age >= 0, the condition is determined to be true, but age = -3, so the condition is determined to be false, and the error log "A person's age cannot be less than zero".

Of course, the error log can also be omitted, but this is not conducive to debugging, such as

Copy the codeThe code is as follows:

assert(age >= 0)

Time to use assertions

Used when a condition that needs to be detected may be false but the code must return true. Here are some common scenarios, which may use assertion detection:
◎When passing an integer type index, such as the Index as an array, this value may be too small or too large, causing the array to cross bounds;
◎Arguments passed to the function, but an invalid parameter will not be executed in the function
◎ An optional type is now nil, but in the following code, non-nil values ​​are required to continue running.

See detailsSubscriptsandFunctions

Note: Assertions can cause an abort of the program's run, so if the exception is expected to occur, then assertions are inappropriate. In this case, exceptions are more appropriate. Assertions ensure that errors will be discovered during development, and it is best not to use them in published applications.