[TOC]
Based on some
Swift contains all the basic data types in C and Objective-C.
Int |
Integer value |
---|---|
Double 和 Float |
floating-point |
Bool |
Boolean value |
String |
Text type data |
Array |
An array of |
Set |
A collection of |
Dictionary |
The dictionary |
Swift adds a higher-order data type not found in Objective-C: tuples. Tuples allow you to create or pass groups of data.
Swift adds an Optional type to handle missing values.
Swift is a type-safe language.
Variables and constants
Constants and variables must be declared before use, let: constant var: variable
let maxNumber = 10
var currentTemp = 0
Copy the code
You can declare multiple constants or variables on a single line, separated by commas
let x = 0.0, y = 9.9, z = 9.9
Copy the code
Pay attention to
If you have a value in your code that does not need to be changed, declare it as a constant using the let keyword.
Type annotations
When you declare a constant or variable, you can add type annotations that specify the type of the value to be stored in the constant or variable.
var welcomeMessage: String
Copy the code
You can define multiple variables of the same type in a single line, separated by commas, and add type annotations after the last variable name:
var red, green, blue: Double
Copy the code
Pay attention to
In general, you rarely need to write type annotations.
If you assign an initial value when declaring a constant or variable, Swift can infer the type of the constant or variable.
Naming constants and variables
Constant and variable name activations include all characters, including Unicode characters:
let π = 3.14159
lethello= Hello world.
let🐶 🐮= "dogcow"
Copy the code
Constants and variable names cannot contain mathematical symbols, arrows, or start with a number.
Output constants and variables
Separator :terminator: Print (_:separator:terminator:) to print the value of the current constant or variable:
let a = "Candy"
print(candy)
/ / output "Candy"
Copy the code
The interpolation
let day = "Sunday"
print("The day is \(day)")
Copy the code
annotation
// This is a line comment
/** * this is a multi-line comment */
Copy the code
A semicolon
Swift doesn’t force you to use a semicolon (;) at the end of every statement.
let cat = "🐱"; print(cat)
Copy the code
The integer
The integer range
Swift provides 8, 16, 32, and 64 bit signed and unsigned certificate types. The naming method is very similar to the C sound.
let minValue = UInt8.min / / minValue to 0
let maxValue = UInt8.max / / maxValue for 255
Copy the code
Int
In general, you do not need to specify the length of an integer. By default
-
On 32-bit platforms: Int and Int32 have the same length
-
On 64-bit platforms: Int and Int64 have the same length
Even on 32-bit platforms, the range of integers that an Int can store ranges from -2,147,483,648 to 2,147,483,647.
UInt
Swift also provides a special unsigned type, UInt, of the same length as the native word for the current platform:
- On 32-bit platforms,
UInt
和UInt32
The length is the same. - On 64-bit platforms,
UInt
和UInt64
The length is the same.
Pay attention to
Avoid using UInt unless you really need to store an unsigned integer of the same length as the current platform native.
Except in this case, it is best to use Int.
Even if the values you need to store are non-negative.
Using Int consistently improves code reuse and avoids conversions between different types of numbers.
Floating point Numbers
Floating-point types represent a larger range than integers and can store larger or smaller numbers than ints. Swift provides two types of signed floating point numbers:
Double
Represents a 64-bit floating point number. Use this type when you need to store very large or high precision floating-point numbers.Float
Represents a 32-bit floating point number. This type can be used if accuracy is not high.
Pay attention to
Double is very accurate, with at least 15 decimal places, while Float has only 6 decimal places. The type you choose depends on the range of values your code needs to handle, and in cases where both types match, Double is preferred.
Type safety and type determination
Swift is a Type safe language. It does Type checks at compile time, flags mismatches as errors, and allows you to find and fix errors during development.
Type checking can help you avoid errors when dealing with different types of values. However, this does not mean that you need to specify a type every time you declare a constant or variable. If you do not display the specified type, Swift will use Type inference ** to select the appropriate type.
Such as:
let a = 42
// a is assumed to be Int
let b = 3.14
// b is supposed to be Double
let c = 3 + 0.14
// c is supposed to be Double
Copy the code
Numeric literals
Integer literals can be written as:
- Decimal: No prefix
- Binary: prefix 0B
- Octal: prefix 0O
- Hexadecimal: prefix 0x
Such as:
let a = 17
let b = 0b1001
let c = 0o21
let d = 0x11
Copy the code
Numeric class literals can be formatted to enhance readability. Both integers and floating-point numbers can add extra zeros and contain underscores without affecting literals:
let a = 000123.456
let b = 1 _000_000
let c = 1 _000_000. 000 _000_1
Copy the code
Numeric type conversion
In general, use Int even if integer constants and variables in your code are known to be non-negative.
Always using the default integer type ensures that integer constants and variables can be used and reused directly
And can match type inference for integer class literals.
The integer conversion
Non-integer variables and constants can store non-integer numbers.
The value ranges from -128 to 127 for Int8 constants or variables
The value of a UInt constant or variable ranges from 0 to 255
let cannotBeNagetive: UInt8 = -1
// UInt8 type cannot store negative numbers, so error is reported
let tooBig : Int8 = Int8.Max + 1
Int8 cannot store more than the maximum number, so an error is reported
Copy the code
Since every integer type can store values out of range, you must use numeric conversions selectively depending on the situation.
This selective use prevents hermitage conversion errors and makes it clear what type conversion intentions are in your code.
/** * Call Int16(one) to create a new UInt16 number to add */
let twoThousand: UInt16 = 2 _000
let one: UInt8 = 1
let twoThousandAndOne = twoThousand + UInt(one)
Copy the code
Integer and floating point conversion
let three = 3
let pointOneFourOneFiveNice = 0.14159
let pi = Double(three) + pointOneFourOneFiveNice
// PI equals 3.14159, so it is presumed to be Double
let integerPi = Int(pi)
// integerPi equals 3, so it is presumed to be an Int
Copy the code
Note:
When a new floating point value is initialized in this way, the floating point is phased.
So 4.71 would become 4, and -3.9 would become -3
Type the alias
A type aliases defines another name for an existing type. Such as:
typealias AudioSample = UInt16
var maxAmplitudeFound = AudioSample.min
Copy the code
Boolean value
Swift has a basic Boolean type, plus Bool.
Swift has two Boolean constants, true and false
let orangesAreOrange = true
let turnipsAreDelicious = false
// Conditional statement
if turnipsAreDelicious {
print("Mmm, tasyty turnips!")}else {
print("Eww, turnips are horrible")}Copy the code
tuples
Tuples combine multiple values into a compound value. Tuples can be of any type; they do not have to be of the same type.
Such as:
let httpError = (404."Not Found")
let (statusCode, statusMessage) = httpError
print("The status code is \(statusCode)")
// "The status code is 404"
print("The status message is \(statusMessage)")
// Print "The status message is Not Found"
Copy the code
When you only need part of a tuple, you can underline the missing part:
let (statusCode, _) = httpError
print("The status code is \(justTheStatusCode)")
Copy the code
Tuples can be accessed by subscripting:
print("The status code is \(http404Error.0)")
// "The status code is 404"
print("The status message is \(http404Error.1)")
// Print "The status message is Not Found"
Copy the code
Optional type
Use optional types (optionals) to handle possible missing cases. Optional indicates two possibilities:
- Possible values: Access optional values by parsing
- There is no value
Note:
There is no such thing as an optional type in C and Objective-C.
The closest thing is a feature in Objective-C where methods return the value object or nil, where nil means “a valid object is missing.”
Swift’s optional types allow you to hint at any type of missing.
Such as:
let possibleNumber = "123"
let convertedNumber = Int(possibleNumber)
// convertedNumber is presumed to be of type "Int?" Or type "Optional Int"
Copy the code
Because the constructor may fail, it returns an optional Int instead of an Int.
An optional Int is written as an Int, okay? . The question mark indicates that the implied value is of an optional type. That is, it may or may not contain a value.
nil
You can assign nil to an optional variable to indicate that it has no value:
var a: Int? = 404
// a contains an optional Int value 404
a = nil
// A now contains no value
Copy the code
Note:
Nil cannot be used for non-optional constants and variables.
If you have constants or variables in your code that need to handle missing values, declare them as the corresponding optional type.
If an optional constant or variable is declared and no value is assigned, they are automatically set to nil:
var temp: String?
// Temp is automatically set to nil
Copy the code
Note:
Nil for Swift is not the same as nil in Objective-C.
OC: nil is a pointer to a nonexistent object.
Swift: nil is not a pointer. It is a definite value used to indicate that a value is missing.
Any type of optional state can be set to nil, not just object types.
If statements and forced parsing
You can use if statements to compare nil to determine if an optional value contains a value.
If an optional type has a value, it will not equal nil
if temp ! = nil {
print('temp contain some value')
}
Copy the code
When you are sure that the optional type does contain a value, you can add an exclamation mark (!) after the optional name. To get the value.
This exclamation mark means “I know this optional has a value, please use it.” This is called forced unwarpping of the optional value:
var temp: String?
if temp ! = nil {
print("temp value is \(temp!)")}// The output temp value is 123
Copy the code
Note:
Use! To retrieve an optional value that does not exist, causing a runtime error. Use! Make sure the optional contains a non-nil value before forcing parsing.
Optional binding
Use an optional binding to determine if the optional type contains a value, and if so, assign the value to a temporary constant or variable.
Optional bindings can be used in if and while statements, which can be used not only to determine whether an optional type has a value, but also to assign the value of the optional type to a constant or variable.
Such as:
if let constantName = someOptional {
statements
}
Copy the code
If the optional Int returned by Int(number) contains a value, create a new temp constant and give it the optional included value
if let temp = Int(number) {
print("\(number) has an integer value of \(temp)")}else {
print("\(number) could not be converd to an integer")}Copy the code
You can include multiple optional bindings or Boolean conditions in an if statement, separated by commas.
The entire if condition is judged to be false as long as any of the optional bindings have a value of nil or any bool condition is false.
Such as:
if let firstNumber = Int("4"), let secondNumber = Int("42"), firstNmuber < secondNumber {
print("\(firstNumber) < \(secondNumber)")}Copy the code
Pay attention to
Use constants and variables in an if conditional statement to create an optional binding that only gets the value in the sentence (body) of the if statement.
Instead, use constants and variables in the GUARD statement to create an optional binding that only gets its value outside and after the guard statement.
Implicitly resolves optional types
Optional types imply that a variable or constant can have no value. Optionally, the if statement determines whether there is a value, and if there is a value, the value can be resolved by the optional binding.
Sometimes, after the first assignment, you can be sure that an optional type always has a value. In this case, it is very inefficient to judge and parse the optional value every time, because you can be sure that it will always have a value.
The optional states of this type can be defined as implicitly unwrapped optionals.
Use the question mark (String?) after the optional type that you want to use. Change to an exclamation mark (String!) To declare an implicit resolution optional type, place the exclamation point directly after the optional type when it can be redefined.
let possiableString: String? = "An optional String."
let forceString: String = possableString! // An exclamation point is required to get the value
let assumedString: String! = "An implicitly unwrapped optional string."
let implicitString: String = assumedString // No exclamation point required
Copy the code
You can think of implicitly resolving an optional type as an optional type that can be resolved automatically.
When you use an implicit resolution of an optional value, Swift first treats it as a normal optional value;
If it cannot be used as an optional type, Swift forces the optional value to be resolved.
In the code above, the optional value ‘
let possiableString: String? = "An optional String." let forceString: String = possableString! // Need an exclamation mark to get the value let assumedString: String! = "An IMPLICITLY unwrapped optional string." let implicitString: string = assumedString // No exclamation mark requiredCopy the code
You can think of implicitly resolving an optional type as an optional type that can be resolved automatically.
When you use an implicit resolution of an optional value, Swift first treats it as a normal optional value;
If it cannot be used as an optional type, Swift forces the optional value to be resolved.
In the code above, the optional value ‘
let possiableString: String? = "An optional String." let forceString: String = possableString! // Need an exclamation mark to get the value let assumedString: String! = "An IMPLICITLY unwrapped optional string." let implicitString: string = assumedString // No exclamation mark requiredCopy the code
You can think of implicitly resolving an optional type as an optional type that can be resolved automatically.
When you use an implicit resolution of an optional value, Swift first treats it as a normal optional value;
If it cannot be used as an optional type, Swift forces the optional value to be resolved.
In the code above, the optional value ‘
let possiableString: String? = "An optional String." let forceString: String = possableString! // Need an exclamation mark to get the value let assumedString: String! = "An IMPLICITLY unwrapped optional string." let implicitString: string = assumedString // No exclamation mark requiredCopy the code
You can think of implicitly resolving an optional type as an optional type that can be resolved automatically.
When you use an implicit resolution of an optional value, Swift first treats it as a normal optional value;
If it cannot be used as an optional type, Swift forces the optional value to be resolved.
In the above code, the optional value assumedString is forced to parse before passing its value to implicitString because
The implicitString type itself is a non-optional String.
In the following code, optionalString does not have a data type to display. Then it is a common optional type by type.
let optionString = assumedString
// optionalString is of type "String?" , the assumedString is also not forced to parse.
Copy the code
Error handling
Error handling can be used to handle error conditions that may be encountered during execution
When a function encounters an error condition, it can report an error. The error message can be thrown from where the function is called and merged
func canThrowAnError(a) throws{}Copy the code
A function can throw an error message by adding a THROWS keyword to the declaration.
When an error message is thrown, you should preend the expression with the try keyword
do{
try canThrowAnError()
// No error message is thrown
} catch {
// An error message was thrown
}
Copy the code
A DO statement creates a new containment scope so that errors can be propagated to one or more catch clauses
Such as:
func makeASandWich() throws {
// ...
}
do {
try makeASandWich()
eatASandWich()
} catch SandwichError.outOfCleanDishes{
} catch SandwichError.missingIngredients(let ingredients){
buyGroceries(ingredients)
}
Copy the code
Assertions and prerequisites
Assertions and prerequisites are checks that are made at run time. You can use them to check if a necessary condition has been met before executing subsequent code. If the Boolean condition evaluation in the predicate or prerequisite is true, the code continues to execute. If it is false, the current state is invalid and the code is finished.
Assertions help you find errors and incorrect assumptions during development, and prerequisites help you detect problems in production.
The difference between assertions and prerequisites is when they do state detection: Assertions run only in the debug environment, while prerequisites run in the debug environment and production environment. In a production environment, the condition of the assertion will not be evaluated. This means that you can use a lot of assertions in your development phase, but those assertions will have no impact in production.
Use assertions for debugging
let age = -3
assert(age > = 0."A person's age cannot be less than zero")
// Assertions can fire because age = -3
Copy the code
Enforce prerequisites
Prerequisites can be used when a condition may be false, but continuing to execute the code requires it to be true.
You can use the global preconditon(_:_:file:line:) function to write a prerequisite. The function is passed an expression with the result true or false and a message that will be displayed when the result of the expression is false:
// For example, use preconditions to check whether subscripts are out of bounds, or to check that a proper argument is passed to the function.
precondition(index > 0."Index Must be greater than zero.")
// Implementation in a subscript
Copy the code
Pay attention to
Unchecked If you compile code using Unchecked mode (-ounchecked), prerequisites will not be checked. The compiler assumes that all prerequisites are always true, and it will optimize your code. However, the fatalError(_:file:line:) function always interrupts execution, no matter how you optimize it.
You can use fatalError(_:file:line:) for prototyping and early development, when there are only declarations of methods but no implementation, you can write fatalError(“Unimplemented”) in the body of the method for implementation. Because fatalError is not optimized away like assertions and prerequisites, you can be sure that the program will be interrupted when the code executes to a method that is not implemented.