Swift type
Variable Declaration
Use let to declare constants, and use VaR to declare variables.
Multiple constants or variables can be declared in a row, separated by commas (,).
var x = 0.0, y = 0.0, z = 0.0
Type Security
SWIFT is a type safe language. The Type-safe language allows you to clearly understand the type of the value to be processed by the Code.
What type is a variable, expressed in two ways:
-
Type Annotation
-
The Type annotation indicates that this variable can store a certain type of value. The colon in the Declaration represents "Yes... type ":
var welcomeMessage: String
-
Type inference
-
If you do not explicitly specify a type, swift uses type inference to select the appropriate type. With type inference, the compiler can automatically deduce the type of the expression when compiling the code. The principle is very simple. You only need to check the value you assigned.
Note: When the floating point type is inferred, swift always chooses double instead of float. Generally, 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.
Variable name
- When you declare a constant or variable as a definite type, you cannot declare it again with the same name, or change the type of the stored value.
- If you need to use the same name as the reserved keyword of swift as the constant or variable name, you can use reverse quotation marks (') to enclose the keyword as the name.
- Once the value of a constant is determined, it cannot be changed. If you try this operation, an error will be reported during compilation.
Print variables and constants
Println is a global function used for output. The output content is wrapped in a line break.
The playground of xcode uses println. Click Show the assistant editor in the toolbar to display the output.
var str = "Hello, playground" println(str)
Type conversion
Sometype (ofinitialvalue) is the default method for calling the swift constructor and passing in an initial value.
Note: you cannot input any type of value. You can only input the value of the corresponding constructor in sometype.
However, you can extend the existing type so that it can receive values of other types (including custom types)
Variables and constants of different integer types can store numbers of different ranges. If the number exceeds the storage range of constants or variables, an error is reported during compilation:
Let cannotbenegative: uint8 =-1 // The uint8 type cannot store negative numbers. Therefore, the error "Let toobig: int8 = int8.max + 1 // The int8 type cannot store more than the maximum value, therefore, the error "Let twothousand: uint16 = 2_000let one: uint8 = 1 // in the language, uint16 has a constructor that can accept a uint8 value, therefore, this constructor can use the existing uint8 to create a new uint16let twothousandandone = twothousand + uint16 (one)
Type alias
A type aliases is another name defined for an existing type. You can use the typealias keyword to define the type alias.
Typealias audiosample = uint16 var maxamplitudefound = audiosample. Min // maxamplitudefound is now 0
Assertions
You can use assertions to ensure that some important conditions have been met before other code is run.
If the condition is true, the Code continues to run. If the condition is false, the Code stops running and your application is terminated.
Let age =-3 assert (age> = 0, "a person's age cannot be less than zero") // assertion is triggered because age <0, the code is stopped and the application is terminated.
It can be used for debugging.
Integer int
Swift provides 8, 16, 32, and 64-Bit Signed and unsigned integer types.
Swift provides a special integer int with the same length as the native character of the current platform:
- On a 32-bit platform, int and int32 are of the same length.
- On a 64-bit platform, int and int64 are of the same length.
Swift also provides a special unsigned uint with the same length as the native character of the current platform:
- On a 32-bit platform, uint and uint32 are of the same length.
- On a 64-bit platform, the length of uint is the same as that of uint64.
Do not use uint unless you really need to store an unsigned integer with the same native character length as the current platform.
In addition to this situation, it is best to use int, even if the value you want to store is known to be non-negative.
The unified use of int can improve code reusability, avoid conversion between different types of numbers, and match the type inference of numbers.
Float double and float
- Double indicates a 64-bit floating point number. Use this type when you need to store large or high-precision floating point numbers.
- Float indicates a 32-bit floating point number. This type can be used if the precision requirement is not high.
Boolean bool
Swift has two Boolean constants: true and false:
let orangesAreOrange = truelet turnipsAreDelicious = false
String and character)
The string type of swift indicates the set of character (character) type values of a specific sequence, which cannot be obtained by subscript.
for character in "Dog!??" { println(character)}let yenSign: Character = "¥"
The character seek connection connects two characters through the + sign
VaR emptystring = "" // empty string literal var anotheremptystring = string () // initialize the string instance emptystring = anotheremptystring // trueif emptystring. isempty {println ("nothing")} Let string1 = "hello" Let string2 = "there" Let character1: character = "! "Let character2: character = "? "Let stringpluscharacter = string1 + character1 // equals to" Hello! "Let stringplusstring = string1 + string2 // equals to" Hello there "Let characterplusstring = character1 + string1 // equals "! Hello "Let characterpluscharacter = character1 + character2 // equals "!? "
Character escape Interpolation
String interpolation is a way to create a new string. It can contain constants, variables, literal quantities, and expressions.
Let multiplier = 3let message = "\ (multiplier) multiplied by 2.5 is \ (double (multiplier) * 2.5 )"
Expressions written in parentheses in Interpolation strings cannot contain non-escaped double quotation marks (") and backslash (\), and cannot contain carriage return or line breaks.Interpolation saves extra plus signs for expression join
Array
Arrays store data of the same type in order
Declare an array
VaR shoppinglist: String [] = ["eggs", "milk"] var shoppinglist = ["eggs", "milk"] var someints = int [] () vaR threedoubles = double [] (count: 3, repeatedvalue: 0.0) // [0.0, 0.0, 0.0] var anotherthreedoubles = array (count: 3, repeatedvalue: 2.5) // type inference [2.5, 2.5, 2.5]
Add, modify, read, and delete data,
// Add shoppinglist. append ("Flour") shoppinglist + = "baking powder" shoppinglist + = ["Chocolate spread", "Cheese", "butter"] shoppinglist. insert ("maple syrup", atindex: 0) // modify shoppinglist [0] = "AAA" shoppinglist [4... 6] = ["Bananas", "Apples"] // interval operator, you cannot add data to the end of the array out of bounds. // you can use the VaR firstitem = shoppinglist [0] For item in shoppinglist {println (item)} // global enumerate function to traverse the array. Enumerate returns a for (index, value) in enumerate (shoppinglist) {println ("item \ (index + 1 ): \ (value) ")} // Delete shoppinglist. removeatindex (0) Let apples = shoppinglist. removelast () someints = [] // reset an unempty Array
Dictionary
Unordered storage of the same type of data values, but must be referenced and addressable by unique identifiers (that is, key-value pairs)
Declare dictionary
var airports: Dictionary<String, String> = ["TYO": "Tokyo", "DUB": "Dublin"] var airports = ["TYO": "Tokyo", "DUB": "Dublin"] var namesOfIntegers = Dictionary<Int, String>()ßß
Read and modify Dictionary data and delete Dictionary data (using nil)
Airports. updatevalue ("Dublin internation", forkey: "Dub ") airports ["APL"] = "Apple internation" airports ["APL"] = nil // APL is now removed from airports. removevalueforkey ("Dub") namesofintegers = [:] // reset to an empty dictionary
Dictionary traversal. The SWIFT dictionary type is unordered. The dictionary keys, values, and key-value pairs are re-arranged during traversal, and the order is not fixed.
// Note that enumeratefor (airportcode, airportname) in airports {println ("\ (airportcode): \ (airportname)")} For airportcode in airports is not used here. keys {println ("airport code: \ (airportcode)")} For airportname in airports. values {println ("Airport name: \ (airportname)")} // use a dictionary to create an array let airportcodes = array (airports. keys) Let airportnames = array (airports. values)
Immutable array and Dictionary
- When it is a variable, how can I play with the dictionary and array?
- When an array is a constant, you cannot change the size of any unchangeable array, but you can reset the value corresponding to the existing index.
- When the dictionary is a constant, it means that we cannot replace the values corresponding to any of the existing keys. The content of an unchangeable dictionary cannot be changed after it is set for the first time.
Tuple
Use the. Operator... array and dictionary to obtain the subscript. Use [];
Declare tuples
VaR http404error = (404, "not found") // default subscript 0, 1 var http200status = (statuscode: 200, Description: "OK") // The default subscript still exists
Access tuples
println(http404Error.0); println(http200Status.0); println(http200Status.statusCode);
Break down the tuples. If you only need a portion of the values, you can mark the ignored values with underscores (_).
let (statusCode, statusMessage) = http404Error let (justTheStatusCode, _) = http404Error
Tuples are similar to arrays in PHP, but Swift is type-safe. Therefore, if different subscripts or different types of values are assigned after the subscript and value are initialized, an error is returned.
Http200status = ("DDD", "dddd"); // Error
Tuples are useful for temporary organization values, but they are not suitable for creating complex data structures. If your data structure is not used temporarily, use a class or struct instead of a tuples.
Optional optional
Either nil or X.
- Nil cannot be used for non-optional constants and variables. If your code contains constants or variables that need to handle Missing Values, declare them as optional types.
- Nil can be used to remove a key-value pair from the dictionary.
Declare optional types
VaR Optional: Int? // The value is nil let possiblenumber = "123" Let convertednumber = possiblenumber. toint () // convertednumber is assumed to be of the type "int? ", Or type" Optional int"
Optional types of variables cannot be used directly. You must first determine whether they have a value and then use it! Resolution,Note! The number is placed after the variable name, and placed before it indicates the operator is not
Because of use! To obtain an optional value that does not exist, causing a running error. Use! Before force resolution, you must determine whether to include a non-nil value. Therefore, it is best to use if for judgment.
if convertedNumber { println("\(possibleNumber) has an integer value of \(convertedNumber!)")} else { println("\(possibleNumber) could not be converted to an integer")}
Optional binding statement. Resolution can be omitted !. Optional binding can be used in the IF and while statements to determine the value of the optional type and assign the value to a constant or variable.
if let actualNumber = possibleNumber.toInt() { // println("\(possibleNumber) has an integer value of \(actualNumber)")} else { println("\(possibleNumber) could not be converted to an integer")}
Optional types of implicit Parsing
The optional type of implicit Parsing is an optional type that can be automatically parsed. All you have to do is place the exclamation point at the end of the Type when declaring it, instead of the end of the optional name for each value.
Let possiblestring: string? = "An optional string." println (possiblestring !) // You need an exclamation point to get the value of let assumedstring: string! = "An implicitly unwrapped optional string." println (assumedstring) // No exclamation point is required // output "An implicitly unwrapped optional string ."
You do not need to use it! Force resolution is the same as the optional type.Similarly, if you try to set a value when no value of the optional type is implicitly parsed, a runtime error is triggered. It is the same as adding an exclamation point after the normal optional type with no value.
If assumedstring {println (assumedstring)} // output "An implicitly unwrapped optional string. "If let definitestring = assumedstring {println (definitestring)} // output" An implicitly unwrapped optional string."