Underlying type
Although Swift is a new programming language designed to develop iOS and OS X apps, Swift's many features are similar to those of C and objective-c.
Swift also provides basic data types similar to C and objective-c, including shaping int, floating-point number double and float, Boolean type bool, and string type. Swift also provides two more powerful basic collection data types, array and dictionary, with more detailed reference to the following: Collection Types.
Like the C language, Swift uses a specific name to define and use variables. In the same way, Swift can define constants, and unlike C, the constants in Swift are more powerful, and using constants in programming makes the code look more secure and concise.
In addition to the common data types, Swift integrates the "tuple" type not found in objective-c and can be passed as a whole. A tuple can also be a return value for a function, allowing the function to return multiple values at a time.
Swift also provides an optional type to handle some unknown nonexistent values. An optional type means that the value either exists, is equal to X, or does not exist at all. An optional type is similar to the nil value of a pointer in objective-c, but nil is only useful for classes (class), and optional types are available to all types and are more secure. Optional types are at the heart of most of Swift's new features.
The optional type is just one example of swift as a type-safe programming language. Swift can help you discover the type errors in your coding more quickly. If your code expects to pass a string of parameter types, then type safety prevents 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 refers to a particular type of value, such as the number 10 or the character "Hello". The value of a variable can be modified as needed, and the value of a constant cannot be modified two times.
Declarations of constants and variables
Constants and variables need to be declared before they are used, and a let keyword is used in Swift to declare a constant, and the VAR keyword declares a variable. As in the following example:
Copy Code code as follows:
Let maximumnumberofloginattempts = 10
var currentloginattempt = 0
The above code can be understood as:
Declares a constant that is called maximumnumberofloginattempts with a value of 10. Then declare a variable currentloginattempt initial value of 0.
In this example, the maximum number of login attempts 10 is invariant and is therefore declared as a constant. The number of attempts that have been logged on is variable, so it is defined as a variable. You can also declare multiple variables or constants in a row, separated by a number:
Copy Code code as follows:
var x = 0.0, y = 0.0, z = 0.0
Note: If a value is not changed in the subsequent code, it should be declared as a constant by the Let keyword. Variables are used only to store values that will change.
Type annotation
When declaring constants and variables, you can use annotations to indicate the type of the variable or constant. Use: Number plus space plus type name you can complete the type annotation after the variable or constant name. The following example declares a variable called welcomemessage, with the annotation type string:
var welcomemessage:string
The semicolon ":" In this role is like saying: ... Is... Type, so the above code can be understood as:
Declare a variable called Welcomemessage, which is of type string
This type of annotation indicates that the welcomemessage variable can accurately store any value of the string type, such as Welcomemessage = "Hello"
Note: It is very rare to use type annotations in actual programming, when defining constants or variables, Swift has determined the type information based on the initialization value. Swift can almost implicitly determine the type of a variable or constant, as detailed in: Type Safety and type inference. In the Welcomemessage example above, the initialization value is not given, so a better approach is to specify the type of the welcomemessage variable rather than let swift implicitly infer the type.
Names of constants and variables
Swift can use almost any character as a constant and variable name, including Unicode, for example:
Copy Code code as follows:
letπ= 3.14159
Let hello = "Hello World"
let = "Dogcow"
However, the name cannot contain mathematical symbols, arrows, invalid Unicode, horizontal-and tab characters, and cannot begin with a number, although the number can be included in the name. Once the declaration is complete, you cannot declare a variable or constant of 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 the SWIFT reserved word, you can surround the name with a ' symbol. However, unless in particular intent, try not to use reserved words as variable/constant names.
You can change the value of a variable to another value of the type it declares, as in the following example, the value of the variable friendlywelcome from "hello!" was modified to "bonjour!":
Copy Code code as follows:
var friendlywelcome = "Hello!"
Friendlywelcome = "bonjour!"
Friendlywelcome is now "bonjour!"
Unlike a variable, a constant's value cannot be modified once it is determined. If you want to try to change the value of a constant, you will get an error when compiling the code
Copy Code code as follows:
Let LanguageName = "Swift"
LanguageName = "swift++"
This is a compile-time error-languagename cannot to be changed
Output Constants and variables
Swift uses println to output variables or constants:
Copy Code code as follows:
println (Friendlywelcome)
Prints "bonjour!"
PRINTLN is a global function that outputs a value and then outputs a newline. In Xcode, the println output is in the console. The print function is similar, except that the line wrap is not printed at the end.
println function General Output a string
Copy Code code as follows:
println ("This is a string")
Prints "This is a string"
The PRINTLN function can also format the output of some log information, like the behavior of the NSLog function in cocoa, which can include constants and variables themselves. Swift inserts the variable name as a placeholder in the string, using a backslash () to prompt Swift to replace the variable/constant name with its actual value, such as:
Copy Code code as follows:
println ("The current value of Friendlywelcome be (friendlywelcome)")//prints "The current value of Friendlywelcome is Bo njour! "
Note: For more details on formatting characters, see String interpolation
Comments
Statements that do not participate in compilation are called annotations, and comments can prompt you for the intent of your code. Comments in Swift are the same as in C, with Single-line annotations
Copy Code code as follows:
and multiline annotations, using/and/or separating
Copy Code code as follows:
/* This is also a comment,
But written over multiple lines * *
Unlike the C language, multiline annotations can be nested, you need to start a multiline comment, then start the second multiline comment, close the second when you close the note, and then the first one. As follows
Copy Code code as follows:
/* This is the start of the multiline comment
/* This is the second, nested multiline comment * *
This is the ' the ' the ' multiline comment * *
This makes it easy to continue adding comments in large chunks of commented blocks of code
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 semicolons, or you want to write multiple statements on a single line.
Copy Code code as follows:
Let cat = ""; println (CAT)
Prints ""
Integer
Integers are numbers like 42 and 23 with no fractions, including signed (positive, negative, 0) and unsigned (positive, 0). Swift provides a number of 8, 16, 32, and 64 digits, similar to the C language, using a 8-bit unsigned integer UInt8, or a 32-bit integer Int32. Like other swift types, these type names are capitalized first.
Integer bounds
Use min or max values to get the maximum minimum value for the type, such as:
Copy Code code as follows:
Let MinValue = uint8.min//minvalue are equal to 0, and is of type UInt8
Let MaxValue = Uint8.max//MaxValue are equal to 255, and is of type UInt8
These value boundary values differentiate the types of integers (such as UInt8), so they can be used in expressions as well as other values of that type, regardless of the benefit.
int type
In general, programmers do not need to select the digits of integers when writing code, and Swift provides an extra integer type int, which is the same number of integer digits as the word length of the current machine environment.
1. On 32-bit machines, int and Int32 are the same size
2. On 64-bit machines, int and Int64 are the same size
Unless you do need to use a positive number with a certain word length, use the int type as much as possible. This guarantees the portability of the code. Even on a 32-bit platform, an int can store values ranging from 2,147,483,648 to 2,147,483,647, which is sufficient for most positive numbers.
UINT Type
Swift also offers an unsigned type of uint, as well as the character looks of the current machine environment.
1. On 32-bit machines, uint and UInt32 are the same size
2. On 64-bit machines, uint and UInt64 are the same size
Note: It is only necessary to specify an unsigned number that is equal to the length of the machine in order to use uint, and in other cases, use int as much as possible, even if the variable is determined to be unsigned. Use int to ensure code portability and avoid conversions between different numeric types. See Type Safety and type inference for details.
5, Floating points
A float is a number with fractions like 3.14159,0.1,-273.15. Floating-point numbers can express values that are wider (larger or smaller) than the int range. Swift supports two types of signed floating-point numbers:
A 1.Double type can represent a 64-bit signed floating-point number. You can use the double type when the number of tables you want is very large or the precision requirements are very high.
The 2.Float type can represent a signed floating-point number of 32. Float type can be used when the number that needs to be expressed does not require 64-bit precision.
Double with at least 15 decimal digits, float at least 6 decimal digits. The appropriate number of floating-point decimal places depends on the range of floating-point numbers you need to handle in your code.
6. Type safety and type derivation
Swift is a type-safe language. Type safety means that you need to figure out the type of a variable when you are 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 at compile time and will complain when any type does not match. This allows programmers to quickly capture and fix bugs as early as possible during development.
Type checking can help you avoid errors when you use different types of values. However, this does not mean that you must specify the type declared by each constant and variable. If you do not specify the type you want, Swift uses type inference to specify the appropriate type. Type inference enables the compiler to automatically derive the type of a particular expression from the initialization value you provide at compile time.
Type inference allows Swift to have 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 Swift has been completed for you.
Type derivation is particularly useful when you declare a constant or variable and give an initial value type. This is usually done by assigning constant values to the declared constants or variables. (Constant values are values that appear directly in the source code, as shown in 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 to an integer
Copy Code code 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 Code code as follows:
Let pi = 3.14159
Pi is inferred to being type Double
Swift always chooses double (not float) when it needs a floating-point type. If you add integers and floating-point numbers in an expression, you deduce a double type:
Copy Code code as follows:
Let anotherpi= 3 + 0.14159
Anotherpi is also inferred of typedouble
Constant value 3 does not display the indicated type, so swift introduces the output type double based on the floating-point value in the expression.
The expression of a numerical quantity
Integer constants can be written as:
1. A decimal number with no prefix
2. A binary number, with the prefix 0b
3. A octal number, with a 0o prefix
4. A hexadecimal number, prefixed by a 0x
All of the following integer constants can be used to express 17 of the decimal value:
Copy Code code as follows:
Let decimalinteger= 17
Let Binaryinteger = 0b10001//binary notation
Let Octalinteger = 0o21//octal notation
Let Hexadecimalinteger = 0x11//inhexadecimal notation
A floating-point can be either decimal (without a prefix) or hexadecimal (with a 0x prefix) and must always have a decimal number (or hexadecimal number) on both sides of the decimal point. They can also have an optional exponent, represented by an uppercase or lowercase e representing a decimal floating-point number, or uppercase/lowercase p to denote a hexadecimal floating-point number
The decimal number with the exponential exp, the actual value is equal to the cardinality multiplied by 10 of the Exp secondary party, such as:
1.25e2 means 1.25x102, or 125.0.
1.25e-2 means 1.25x10-2, or 0.0125.
The hexadecimal number with exponential exp, the actual value equals the base number multiplied by the exp secondary of 2, such as:
0XFP2 says 15x22, or 60.0.
0xfp-2 says 15x2-2, or 3.75.
All of the following floating-point constants represent decimal 12.1875:
Copy Code code as follows:
Let decimaldouble= 12.1875
Let exponentdouble= 1.21875e1
Let hexadecimaldouble= 0xc.3p0
Numeric type conversions
Use the int type for all generic numeric integer constants and variables in your code, even if they are known to be non-negative. This means that the numeric constants and variables in your code can be compatible with each other and can match the types that are automatically deduced.
These numeric types should be used only for certain reasons (performance, memory footprint, or other necessary optimizations) when other numeric types do need to be used. In these cases, using a type that explicitly specifies a length helps to discover a value range overflow and should leave a document.
Integer conversions
The range that can be stored in an integer constant or variable varies according to each numeric type. A Int8 constant or variable can store numbers ranging from 128 to 127, while a UInt8 constant or variable can store a number between 0 and 255. Incorrect assignment will cause the compiler to make an error:
Copy Code code as follows:
Let cannotbenegative:uint8 =-1
UInt8 cannot store negative numbers, and so this'll is an error
Let toobig:int8 = Int8.max + 1
Int8 cannot store a number larger thanits maximum value,
And so this would also an error
Because each numeric type can store values of different ranges, you must do a gradual conversion on the underlying numeric type. This protects against hidden conversion errors and helps clarify the intent of the type conversions in your code.
To convert a particular 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 the UInt16 type, and the constant one is the UINT8 type. They cannot be added directly because the types are different. Instead, the example calls UInt16 (one) to create a new variable of the type of UInt16 that is initialized with the value of the variable, and uses this value instead of the original value to participate in the operation:
Copy Code code as follows:
Let twothousand:uint16 = 2_000
Let One:uint8 = 1
Let twothousandandone= Twothousand + UInt16 (one)
You can do the addition operation because the types of both are UInt16. The output constant (Twothousandandone) is inferred as a UInt16 type because it is the sum of two UInt16 values.
SomeType (ofinitialvalue) is the default type conversion method for Swift. In implementation, the UInt16 has a constructor that accepts the UINT8 value, which is used to construct a new UInt16 variable from the existing UInt8. You cannot pass in any type of argument, it must be a type of UInt16 initialization acceptable type. How to extend an existing type, which allows you to accept a new type (including your own type definition), see extensions.
Integer and floating-point conversions
Conversions between integers and floating-point types must be explicitly declared:
Copy Code code 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 both sides of the expression are the same type. Without this conversion, the addition operation will not be allowed. Conversely, an integer type can be initialized with a double or float value:
Copy Code code as follows:
Let integerpi= Int (PI)
Integerpi equals 3, and is inferred tobe of type Int
When you initialize a new integer value in this manner, the floating-point value is always truncated. This means that 4.75 becomes 4, and-3.9 becomes-3.
Note: The conversion rules for numeric type constants/variables are different for the type conversion rules and numeric type literals. A constant value of 3 can be added directly to a constant value of 0.14159, because the constant value does not have an explicit type. Their type is deduced by the compiler.
Type Alias
The type alias is an alternative name defined for an existing type. You can define type aliases using the Typealias keyword. A type alias can help you use a more contextual name to refer to an existing type, such as handling a foreign type with a specified length:
Copy Code code as follows:
Typealias audiosample = UInt16
Once you have defined a type alias, you can use the alias in any place where the original name can be used:
Copy Code code as follows:
var maxamplitudefound= audiosample.min
Maxamplitudefound is now 0
Here, the audiosample is defined as a UInt16 alias. Because it is an alias, calling Audiosample.min is actually calling Uint16.min, which assigns the Maxamplitudefound variable an initial value of 0.
Boolean type
Boolean types in swift use the bool definition, also known as the logical (logical) type, and the optional value is true and false:
Copy Code code as follows:
Let Orangesareorange = True
Let turnipsaredelicious = False
Here the types of Orangesareorange and turnipsaredelicious are deduced to be bool because they are initialized to the literal type of bool. As with int and double, you do not need to explicitly give the data type when defining a Boolean type, just assign the value to True or false. Type inference makes swift code more precise and readable when you initialize a constant/variable with a constant value of a certain type. Boolean types are particularly useful in conditional statements, such as in an if statement
Copy Code code as follows:
If turnipsaredelicious {
println ("Mmm, Tasty turnips!")
} else {
println ("Eww, turnips are horrible.")
}
Prints "Eww, turnips are horrible."
Conditional statements such as if statements, which we will controlflow in detail later in this chapter. Swift's type-security policy prevents other non-Boolean types from being converted to Boolean types, such as
Copy Code code as follows:
Let i = 1
If I {
This example would not compile, and'll is an error
}
will have an error, but this is possible in other programming languages. But the following definition is correct:
Copy Code code as follows:
Let i = 1
if i = = 1 {
This example would compile successfully
}
The result of i = = 1 is a Boolean type, so it can be checked by type. Like I==1 This comparison will be discussed in the chapters [Basic Operators]. The example above is also an example of swift type safety. Type safety avoids accidental type errors, guaranteeing that the intent of the code is clear.
Tuple type
A tuple type can assemble a number of different data types into an element that 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. An HTTP status code is a particular state code that is returned when a Web page is requested. The specific meaning of the 404 error is that the page was not found.
Copy Code code 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 of strings that contain numbers and contain string descriptions that are easy to understand. This tuple can be described as a tuple of type (int,string).
Programmers are free to create the type of tuple they want, such as (int, int, int), or (String, Bool). The number of types that make up the tuple is also unlimited. You can access the values of a tuple, respectively, in the following ways:
Copy Code code 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 isn't Found"
If you need only the individual values in the tuple, you can use (_) to ignore unwanted values
Copy Code code as follows:
Let (Justthestatuscode, _) = Http404error
println ("The Status code is \ (Justthestatuscode)")
Prints "The Status code is 404"
Alternatively, you can use the element ordinal to select the value in the tuple, and note that the ordinal number starts at 0
Copy Code code 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 isn't Found"
When you create a tuple, you can also specify the name of each element directly, and then use the tuple name directly. element name access, such as:
Copy Code code as follows:
Let Http200status = (statuscode:200, description: "OK")
println ("The Status code is \ (Http200status.statuscode)")
Prints "The status code is 200"
println ("The status message is \ (http200status.description)")
Prints "The status message is OK"
Tuple types are particularly useful when returning values as functions, and you can return more information to a function for the user. For example, a function that requests a Web page can return a tuple of type (int,string) to characterize the success or failure of a page acquisition. Returns two different types of tuples can provide more return information than a single value that returns only one type. See functions with multiple return Values
Optional type
An optional type can be used when a value may not exist. The definition of this type is that there is either a value that is equal to X, or that the value does not exist.
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. In 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 particular value. Swift's optional type helps you to define a situation where any value does not exist.
Here's an example where the string type in Swift has a method called ToInt that converts a string to an int type. It should be noted, however, 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 Code code as follows:
Let Possiblenumber = "123"
Let Convertednumber = Possiblenumber.toint ()
Convertednumber is inferred to being type "int", or "optional int"
Because the ToInt method may fail, it returns an optional int type, different from the int type. An optional int type is recorded as int?, not int. The question mark indicates that its value is optional, may return an int, or the returned value does not exist.
If statements and forced unpack
Programmers can use the IF statement to detect whether an optional type contains a particular value, and if an optional type does contain a value, it returns true in the IF statement, or false. If you have detected that the value exists, then you can use or output it, in the output only need to add an exclamation point (!) after the name. That means telling the compiler: I've already checked this value and I can use it. Such as:
Copy Code code as follows:
If Convertednumber {
println ("\ (possiblenumber) has an integer value of \ (convertednumber!)")
} else {
println ("\ (Possiblenumber) could is converted to an integer")
}
Prints "123 has an integer value of 123"
Conditional statements such as if statements, which we will controlflow in detail later in this chapter.
Select Bindings
Select bindings to help determine whether an optional value contains a value, and if so, converts the value to a temporary constant or variable. Select bindings can be used in an if or a while statement to check for values outside an optional type and to extract possible values. The IF and while statements are detailed in Controlflow.
The method is as follows:
Copy Code code as follows:
If let Constantname = someoptional {
Statements
}
The previous example can also be rewritten as:
Copy Code code as follows:
If Let Actualnumber = Possiblenumber.toint () {
println ("\ (possiblenumber) has an integer value of \ (Actualnumber)")
} else {
println ("\ (Possiblenumber) could is converted to an integer")
}
Prints "123 has an integer value of 123"
The above code is easy to understand: If Possiblenumber.toint returns an optional int that contains a value, define a constant actualnumber to equal that value and use it directly in subsequent code.
If the conversion is successful, then the Actualnumber constant is available in the first branch of if, and is initialized to the value contained in the optional type, and is not required! Prefix. In this example, Actualnumber is simply used to print the results.
Both constants and variables can be used to make optional bindings. If you want to modify the value of Actualnumber in the first branch of If, you can write as if Var actualnumber, Actualnumber becomes a variable and can be modified.
Nil
You can assign a special value to an optional type nil:
Copy Code code 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, the default setting is nil
Copy Code code as follows:
var surveyanswer:string? Surveyanswer is automatically set to nil
Note: Swift's nil is different from the 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 pointers.
Implicit unpack optional type
In the example above, an optional type represents a constant/variable that can have no value. An optional type can be detected by an if statement for a value and can be extracted by an optional binding.
However, in some cases, the optional type is always valid, so you can define it implicitly to remove the type check and enforce the optional type. These optional types are an optional type of implicit unpack. You can add it directly behind the type! Instead of? To specify.
The optional types of implicit unpack are mainly used in cases where a variable/constant value must exist after the definition is instantaneous. This is mainly used in the initialization of classes, as detailed in unowned References and implicitly unwrapped Optional Properties.
An optional type of implicit unpack is an optional type, but can be used as a generic type, without having to verify that the value exists each time. The following example shows the difference between an optional type and an optional type of package.
Copy Code code as follows:
Let possiblestring:string? = "An optional string."
println (possiblestring!)//requires a 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 think of an implicit unpack optional type as an optional type of automatic unpack for each use. That is, not every time you use the variable/constant behind the add! But directly in the definition of the time added.
Note: If an optional type of an implicit solution does not contain an actual value, access to it throws a run-time error. Add it after the variable/constant name! The same is true of the situation.
You can still detect whether there is a value by taking the optional type of unpack as a normal optional type.
Copy Code code as follows:
If assumedstring {
println (assumedstring)
}
Prints "an implicitly unwrapped optional string."
or by selecting a binding check
If let definitestring = assumedstring {
println (definitestring)
}
Prints "an implicitly unwrapped optional string."
Note: If there is a possibility that an optional type exists without a value, you should not use the unpack optional type. In this case, be sure to use the normal optional type.
Assertion
An optional type allows programmers to detect whether a value exists at run time, and then use code to handle a non-existent situation. However, in some cases, if a value does not exist or the value does not meet the condition will directly affect the execution of the code, this time need to use the assertion. In this case, the assertion ends the execution of the program and provides the basis for debugging.
Debugging with assertions
An assertion is a method that detects whether a condition is true in real time, that is, the assertion assumes that the condition is true. The assertion guarantees that subsequent code execution depends on the condition being set up. If the condition is met, the code continues to execute, and if this condition is false, then the code will break execution.
In Xcode, if you break during debugging, you can view the debug statement to see the state of the program when the assertion fails. Assertions can also provide the appropriate debug information. Use assert debugging with the global function assert, which accepts a Boolean expression and a message that is displayed when an assertion fails, such as:
Copy Code code 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 was not >= 0
When the current condition returns false, the subsequent error log will be output.
In this example, the condition is determined to be true only when age >= 0, but the condition is judged to be false, and the output 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 Code code as follows:
Time to use assertions
Use when you need to detect that a condition may be false, but the code must run to return true. Here are some common scenarios where assertion detection may be used:
When passing an integer type subscript, such as the index of an array, the value may be too small or too large to cause the array to cross over;
The argument passed to the function, but an invalid parameter will not execute in the function
An optional type is now nil, but in the next code, a nil value is required to continue running.
Refer to subscripts and functions
Note: Assertions can cause the execution of a program to abort, so assertions are not appropriate if the exception is expected to occur. In this case, the exception is more appropriate. Assertions ensure that errors are found during development, and that it is best not to use them in published applications.