Related articles
Swift QuickStart (i) First Swift program
1. Variables and Constants
declaring constants and variables
Swfit is a strongly typed language, and Swift requires that all variables and constants be declared before they are used.
Declaring a variable requires VAR, and declaring the constant requires using the Let
var 变量名[:类型] =初始值let 常量名[:类型] =初始值
Here's an example:
//explicitly specifying a type when declaring a variable var age:int//to specify an initial value when declaring a variable, the compiler determines the variable's type as String based on the initial value. Span class= "Hljs-keyword" >var game= "Nine Yin Canon" // An explicitly specified type is consistent with the type of the initial value, declaring the variable to be correct var age1:int = 30 ; //an explicitly specified type is inconsistent with the initial value type, declaring the variable fails var game1: string = 500 ; //defines a constant that does not explicitly specify a type, and the compiler determines the type of the constant based on the initial value let maxAge = 120 // When defining constants, specify both the type of the constant and the initial value of the constant let game2: string = "Nine Yin Canon"
output constants and variables
You can use the Print function to output the value of the current constant or variable:
print//九阴真经
Swift uses string interpolation (string interpolation) to add a constant name or variable name as a placeholder to a long string, and Swift replaces the placeholder with the value of the current constant or variable. Enclose the constant or variable name in parentheses and escape it with a backslash before opening the parentheses:
print("game的值为:\(game)"//game的值为:九阴真经
2. Integral type
Integers are numbers that do not have fractional parts, such as 23 and-23. Integers can be signed (positive, negative, 0) or unsigned (positive, 0).
Swift provides 8,16,32 and 64-bit signed and unsigned integer types. These integer types are similar to those of the C language, such as the 8-bit unsigned integer type is the uint8,32-bit signed integer type, which is Int32. As with other types of Swift, integer types are capitalized.
Integral type range
You can access the Min and Max properties of different integer types to get the maximum and minimum values for the corresponding type:
let= UInt8.min// minValue为 0let= UInt8.max// maxValue为 255
int type and UINT type
The int type occupies the same memory as the current platform: for 32-bit platforms, the int type is the same length as the Int32 type, and for 64-bit platforms, the int is the same length as the Int64 type. In addition, Swift supports support for unsigned integers. But try not to use uint unless you really need to store a unsigned integer that is the same as the current platform's native word length. In addition to this scenario, it is best to use int, even if the value you want to store is known to be non-negative. Uniform use of int can improve the reusability of code, avoid conversions between different types of numbers, and match the types of numbers to speculate. Even on a 32-bit platform, an int can store an integer range that can reach -2147483648~2147483647, which is big enough for most of the time.
Integer numeric representation
Swift integer values are represented in 4 ways:
- Decimal: The default is a decimal integer.
- Binary: An integer beginning with 0b.
- Octal: An integer beginning with 0o.
- Hexadecimal: An integer beginning with 0x.
let17let0// 二进制的17let0// 八进制的17let0x11// 十六进制的17
3. Floating-point type
Floating-point types represent larger ranges than integer types and can store numbers that are larger or smaller than the int type. Swift provides two types of signed floating-point numbers:
A double represents a 64-bit floating-point number. Use this type when you need to store large or very high-precision floating-point numbers.
Float represents a 32-bit floating-point number. This type can be used if the accuracy requirement is not high.
floating-point numeric representation
Swift's floating-point number is represented in 3 ways:
- Decimal form: This form is the usual simple floating point number, for example 2.23, 50.0. A float must contain a decimal point, or it will be treated as an integer type.
- Scientific counting forms: for example 2.23e2 (2.23x102), 2.23E2 (2.23x102).
- Hexadecimal number form: This form of floating-point numbers must start with 0x, and you need to use p to represent the exponential part, such as 0X2.A2P2 (0x2.a2x102)
4. Numeric Type conversions
conversions between integral types
Variables and constants of different integer types can store numbers of different ranges. A constant or variable of type Int8 can store a range of numbers -128~127, whereas a constant or variable of type UInt8 can store a range of numbers 0~255. If the number exceeds the range of constants or variables that can be stored, errors are made when compiling:
// UInt 类型不能存储负数,所以会报错let=-1// Int8 类型不能存储超过最大值的数,所以会报错 let= Int8.max+1
To convert one number type to another, you use the current value to initialize a new number of the desired type, which is the type of your target. In the following example, the constant two is the UInt16 type, but the constant one is the Uint8 type. They cannot be added directly because they are of different types. So call UInt16 (one) to create a new UInt16 number and initialize it with the value of single, then use this new number to calculate:
two2one1thirdtwo+ UInt16(one
integer and floating-point conversion
The conversion of integers and floating-point numbers must explicitly specify the type:
let3let0.141596let// add等于3.14159,所以被推测为 Double 类型
It is safer to convert to a data type with a large range of tables when making a type conversion, which in turn may result in runtime errors. Swift various numeric tables range from small to large order: int8-int16-int32-int64-float-double
5. Boolean type
Swift has a basic Boolean type, called bool, whose value can only be true and false, and cannot be represented by 0 or non-neutral. Other data types cannot be converted to bool types.
vartruevarfalse
The string "true" and "false" are not converted directly to the bool type, but the bool type variable can be interpolated into a string:
str:String="\(isGame)是真的"print(str)
6. Tuple Types
defining tuple type variables
Tuples (tuples) combine multiple values into a single composite value. Values within a tuple can be of any type and are not required to be of the same type.
// 定义元组变量,并指定初始值,系统推断该元组类型为(Int, Int, String)var game= (12"九阴真经")// 使用元组类型来定义元组变量varString , Double)// 为元组变量赋值时必须为所有成员都指定值score = (9889"及格"20.4)
A member of a tuple type can be a tuple again:
var test : (Int , (IntString))test = (20 , (15"大航海时代"))
Output tuple:
print("game元组的值为:\(game)")print("score元组的值为:\(score)")print("test元组的值为:\(test)")
get the element values in a tuple
Swift allows access to a single element of a tuple through the following table, with the tuple's subscript starting at 0.
print("game元组的排名元素为:\(game.0)")print("game元组的名称元素为:\(game.2)")print("test元组的第2个元素的第2个元素为:\(test.1.2)")
name the elements in a tuple
When you define tuples, you can also use the form of key:value to define tuples, which is equivalent to specifying a name for each element, and that the specified name has better readability:
// 使用元组类型来定义元组变量var score : (java:Int , swift:Int , oc:String , ruby:Double)// 简单为每个元素指定值,此时必须按顺序为每个元素指定值score = (9960"及格"20.1// 通过key为元组的元素指定值,在这种方式下,元组内各元素的顺序可以调换score = (oc:"及格" , swift:60 , java:99 , ruby:20.1
7. Optional type
optional type and value missing
Immediately after any of the existing types? can be represented as an optional type, variables of an optional type are used to handle "missing values."
Let's take a look at the following code:
var"九阴真经"var num :Int = str.toInt()//会报错var num1: Int? = str.toInt()//正确的代码
The second line of code will be error, because the "Nine Yin Canon" This string type cannot be converted to the int type, if the str equals the number type string will be converted successfully (such as var str = "11"). When the conversion fails, we cannot return the int value, which is the case of "missing value", so you must use the INT? type variable to store the conversion result, so the third line of code is correct.
Swfit represents "missing value" with nil, so the value of the NUM1 variable above is nil.
It is important to note that only variables and constants of the optional type can receive nil, and variables and constants of non-optional types cannot receive nil.
forced parsing
The int type is not the same type as the int type, and the program cannot treat the value of the int? type as an int. In order to get the actual stored value of the optional type, we can add "!" after the value of the optional type. No. This exclamation mark indicates that the optional variable is known to have a value, please extract the value, the method of adding an exclamation mark is called forced parsing.
varString"九阴真经"// str是String?类型的,不能赋值给String类型的s变量varString = str//会报错
The above example will be an error, and if we write this then there will be no problem:
varString = str!print(s)
The forced resolution must be a variable of an optional type or a constant that does have a value to parse successfully, otherwise an error will be made. In order to report that forced parsing does not cause a run to be an error, SWIFT provides an if statement to determine whether an optional type has a value, so the above statement is more appropriate than the following form:
var"九阴真经"ifnil{ // 该值是String类型,因此可赋值给String类型的s变量 var s : String = str! print(s)}else{ print("str为nil,不能强制解析")}
implicitly selectable types
The implicit option is to add "!" after any of the existing types. ”。 Take an int type example, int? and int! The difference is: when the program gets int? Type, the program must add "!" after the variable name. "Suffix for forced parsing, while int! You do not need to, Swift will automatically perform an implicit parsing:
varString"九阴真经"// 对于String?可选类型,必须使用感叹号执行强制解析varString = s1!varString"大航海时代"// 对于String!隐式可选类型,无需使用感叹号执行强制解析varString = s2
It is important to note that the value of an implicitly selectable type if there is no value, if the program attempts to get the value also results in a run-time error, as with forced parsing, we use the IF statement to determine whether an implicitly selectable type has a value:
var"大航海时代"ifnil {// 对于String!隐式可选类型,无需使用感叹号执行强制解析var s : String = strprint(s)}else{ print("s为nil,不能强制解析")}
Optional Bindings
An optional binding is used to determine whether an optional value is included, or to assign a value to a temporary constant or variable if it is included. An optional binding is typically used in an if and while statement to judge an optional value and assign a value to a constant or variable.
var"九阴真经"// 如果可选变量str有值,将值赋值给tmp变量。ifvar tmp = str{ print("str的值为:\(tmp)")}else{ print("str的值为nil,不能解析!")}
8. Characters and Strings
Swift uses character to represent characters, string to represent strings, and strings to represent an ordered set of character sets.
Character Type
Swift uses the Unicode character set to store characters, and the characters must be wrapped in double quotation marks.
There are three representations of the values that define the character type:
- Specify a character constant, such as "A", "3", directly from a single character.
- A special character constant is represented by an escape character, such as "\ n", "\ r".
- Uses the Unicode form of \u{n}, where n represents the hexadecimal number of a 1~8.
Common escape characters for Swift:
Space-out character
\ back Slash
\ t tab
\ n line break
\ r return character
\ "Double quotation marks
\ ' Single quotation mark
String Type
To create a string:
var str="九阴真经"var name:String="九阴真经"
The string is actually a struct, so we can call the constructor of the struct to create the string:
var str=String()//创建空字符串var str=String("九阴真经")
string Variability
In OC, there are nssting and nsmutablestring to represent immutable and mutable strings, and Swift provides only string types, and swift distinguishes strings by constants and variables:
var mutableStr="可变字符串"let immutableStr="不可变字符串"
string comparison
Swift provides 3 ways to compare strings:
- string equality = =
- Prefix equal Hasprefix ()
- suffix equal hassuffix ()
var str="jiuyinzhenjing"var hasPrefix:Bool=str.hasPrefix("jiu")print(hasPrefix)//结果为true
9. Type aliases
Swift provides a type alias to specify another name for an existing type, using Typealias to define the type alias:
max=UintMin.max//相当于取Unit16类型的最大值print(max)//结果为65535
The use of type aliases is not recommended here, which makes the program less readable.
Swift Quick Start (ii) Basic data types