Constants and variables
The value of a constant cannot be changed once it is set, and the value of a variable can be changed in the future
We can use a registration demand to understand the constant and variable, the number of participants is constant, the number of participants is a variable, with the increase of the number of participants and increase as the number of participants is the same
Declaration of constants and variables
// var infinitive = infinitive; var infinitive = infinitive; // Var infinitive = infinitive; Var Signup = 0;Copy the code
If the stored value in your code is unchanged, always declare it a constant using the let keyword. Use variables only to store values that need to be changed.
Changing the value of a variable
The number of applicants is increased to equal the quota. The number of applicants is already full
While signup < participateMax {signup += 1} print(" number of participateMax \(signup) number of participateMax \(signup)") // Number of participateMax 10 10Copy the code
Type safety and type inference
Swift is a type-safe language. If we know whether we are using a String or an Int, we cannot pass an Int to String incorrectly. Swift also detects type mismatches at runtime and flags them as errors, which can avoid many problems during development. When you declare the type of the property in advance, if you don’t, the compiler checks the type of your value and automatically converts it to the corresponding type.
Let meaningOfLife = 42 let meaningOfLife = 42 let meaningOfLife = 42 let PI = 3.14159 let PI = 3.14159 Swift will infer that the attribute type is Double. Let anotherPi = 3 + 0.14159Copy the code
AnotherPi itself has no explicit type, so the appropriate output type of Double can be inferred from floating point literals as part of the addition.
Tuples Tuples
A tuple is a data type not found in OC. A tuple mainly combines multiple values into a combined value. The value in a tuple can be of any type.
// The error code is a tuple of an Int and a String. Let errorInfo = (404," does not exist ") // We can also combine two constants or variables into a tuple. Let (errorCode,errorDic) = errorInfo Print ("errorCode\(errorCode),errorDic\(errorDic)") errorCode404,errorDic does not exist Let (justErrorCode,_) = errorInfo print("\(justErrorCode)") // 404 // \(errorInfo.0),errorInfo.1 = \(errorInfo.1)") // errorInfo.0 = 404,errorInfo ErrorCode :404,errorDic:" does not exist "); Print ("errorCode\(errorinfo.errorcode),errorDic\(errorinfo.errordic)") errorCode404,errorDic does not existCopy the code
Tuples are suitable for simple correlation values. If more complex, use a class or structure
Optionals optional
We use optional bindings when the value may not exist. The Swift option allows you to indicate that there is no value for any type without the need for special constants.
Let constantName = Int("332f2"); /// Optional bind Int; /// / Optional bind Int; = nil) {print(" jE \(String(constantName))")}else{print(" je \(String(constantName))")}Copy the code
We might get an error when we call this Int initializer, it returns an optional Int, it’s not a concrete Int, it either returns an Int or nothing.
nil
You can set an optional variable value to nil, and if a constant or variable in your code needs to work without a value under certain conditions, always declare it as an optional value of the appropriate type.
var delegate:UITableViewDelegate? = nil
Copy the code
If an optional variable is defined and no default value is provided, the variable is automatically set to nil:
var nameStr:String? NameStr == nil if nameStr == nil {print("nameStr == nil") // nameStr == nil}Copy the code
If statements and forced unpacking
How can we tell if an optional variable or constant contains a value? We just use the if statement to compare the optional value to nil == Nil does not contain an optional value! =nil contains optional values
var nameStr:String? if nameStr ! = nil {print("nameStr contains string")}Copy the code
If we are sure that the optional variable contains a value, we can use! To force unpacking
var nameStr:String? = "name" if nameStr ! = nil { print("nameStr ==\(nameStr!) ") // nameStr ==name }Copy the code
Optional Binding Optional Binding
We can use optional bindings to determine whether an optional contains a value, and if so, make that value available as a temporary constant or variable. Optional bindings can be used with if and while statements to check for a value that can be selected and extract that value into a constant or variable as part of a single operation
var nameStr:String? = "name"
if let name = nameStr {
print("nameStr == \(name)") // nameStr == name
}
Copy the code
Implicitly Unwrapped Optionals
Implicit expansion optional, we use when declaring! Don’t have to? If the option for implicit unpacking is nil and you try to access its wrapped value, a runtime error is triggered. The result is exactly the same as putting an exclamation point after a normal optional that contains no value. We can use implicit unpacking.
var nameStr:String! = "name" //nameStr = nil //print("nameStr ==\(nameStr!) ") if nameStr! = nil { print("nameStr ==\(nameStr!) ") // nameStr ==name }Copy the code
We can also use optional bindings to unpack the value
if let name = nameStr {
print("nameStr == \(name)") // nameStr == name
}
Copy the code
Do not use the option of implicit unpacking when there is a chance that the variable will later become nil. If you need to check for nil values during the life of a variable, always use the normal optional type.
Exception handling
You can use exception handling to respond to exceptions that your program may encounter during execution. When a function encounters an error condition, it throws an error. The caller of the function can then catch the error and respond appropriately.
We can customize an exception
Enum myError:Error {/// Subscript is invalid case indexError /// Array is out of bounds case indexOut}Copy the code
Custom a function that throws an exception when an error occurs
func canThrowAnError(array:NSArray, index:Int) throws { // this function may or may not throw an error if index < 0 { throw myError.indexError } if index >= Array. Count {throw myerror. indexOut} print(" array[index] = -\(array[index])")}Copy the code
We’ll do that with a catch
Do {try canThrowAnError(array: ["1"], index: -1) // No error was thrown} catch myerror.indexError {// an error was thrown print} catch myerror.indexout Do {try canThrowAnError(array: ["1"], index: 1) // No error was thrown} catch myerror.indexError {// an error was thrown print} catch myerror.indexout {print(" array index is out of bounds ")}Copy the code
Assertions and prerequisites
Assertions are used primarily to check the validity of a program at run time. If the Boolean condition evaluates to true, the program continues; if it evaluates to flase, the program is invalid and does not execute. Assertions help you find errors and incorrect assumptions during development.
Let’s see how to use assertions:
Let age = -5 assert(age > 0, "age is not valid ")Copy the code
Use assertionFailure if a conditional judgment is used to indicate that the assertion fails.
Let age = -5 if age>0 {print(" age ")} else {assertionFailure(" age ")}Copy the code
A prerequisite is used when a condition may be false, but the continuing code requires that the condition be true. For example, a prerequisite is used to check if a subscript is out of bounds, or to check if a correct argument is passed to a function.
Precondition (index > 0, "index must be greater than 0")Copy the code
Assertions help you find errors and incorrect assumptions during the development phase, and prerequisites help you detect problems in the production environment. Assertions differ from prerequisites in when they are statically detected: assertions run only in the debug environment, while prerequisites run in both the debug and production environments. In a production environment, the asserted conditions will not be evaluated.