Swift tells you - basic data type (type)

Swift tells you (2) - Variables & constants (Variables & constants)

Understanding difficulty
Practical degree

According to different situations and needs, variables or constants need different types to perform actions. For example, height and weight need numbers with decimal points; Integer is required to calculate the number of people; Name and name need text string. Use different types (types) according to different situations.

No matter which word you use, it is important to understand the meaning. There are at least two different versions in Swift's Chinese translation. There is no need to worry about which is the standard version. In fact, both are not standard! The standard language is English. Therefore, it is important to understand the meaning and get used to using English nouns as much as possible. In this way, if you want to search for information or check some foreign websites, you can find what you need more accurately.

The following are the basic data types:

Int - integer
Float, Double - floating point number
Bool - Boolean value, Boolean value
Character - character, character
String - string, string
Tuple tuple
Array - array, array
Dictionary - Dictionary

When programming in any programming language, various data types will be used to store different information in different situations.
The data type of the variable determines how the bits representing these values are stored in the computer's memory.
All variables have data types to determine which type to store.

Various data types will be described one by one below

Int - integer

An integer (Int) refers to a number without a decimal point. It can be signed (positive, negative, zero) or unsigned (positive, zero).

Swift provides 8, 16, 32 and 64 bit signed integer types, Int8, Int16, Int32 and Int64 in order, and unsigned integer types, UInt8, UInt16, UInt32 and UInt64 in order. In general, this doesn't need to be considered too much.

Generally speaking, you don't need to specify the length of an integer. Swift provides a special integer type int with the same length as the native word length of the current platform: it is the same as Int32 on 32-bit platform and Int64 on 64 bit platform.

Generally, when we use integer type, it is recommended to use Int only in most cases. If you don't need a decimal point, use Int.

Float, Double - floating point number

Floating point numbers (float, Double) refer to numbers with decimal points. The difference between float and Double lies in accuracy. Float has 6 digits, while Double can reach 15 digits, as follows:

let piValue = 3.1415926
var height = 178.25

// When declaring a floating-point number, if there is no class annotation, it will usually be judged as Double  
let oneHeight = 165.25 // The category is Double
let anotherHeight: Float = 175.5 // Unless the category is marked as Float

If you need a decimal point, use   Just Double.

Integer and floating point conversion

The conversion of integer and floating-point numbers must specify a category. Examples are as follows:

// Category is integer Int
let number1 = 3

// The category is floating point Double
let number2 = 0.1415926

// Int needs to be converted to Double before adding, otherwise an error will be reported
let pi = Double(number1) + number2

// The category of this value is Double
// Print: 3.1415926

On the contrary, you can convert a floating-point number to an integer, and the number after the decimal point will be truncated. As follows:

let integerPi = Int(pi)

// The number after the decimal point with category Int is truncated
// So only print: 3

Bool - Boolean value, Boolean value

Swift has a basic Boolean type called Bool. Boolean values are logical values because they can only be true or false. Swift has two Boolean constants, true and false.

Is "yes" and "no"; "Right" and "wrong"; The concepts of "affirmation" and "Negation".

let storeOpen = true
let forFree = false

Character - character, character

A character refers to a byte (simply an English letter, number or symbol) in the encoding format.

//A character refers to a single letter, for example:

String - string, string

A string is an ordered set of characters (simply a paragraph of text), which are enclosed in a pair of double quotation marks.

//A string is a sequence set of characters, for example:
"Hello, World!"
let firstString = "Nice to meet you."
let secondString = "Nice to meet you,too."

// When declaring a String, it will be judged as String regardless of the number of words
let str1 = "It is a string ." // The category is String
let str2 = "b" // The category is still String
let str3: Character = "c" // Unless the category label is filled in as Character

If you want to add other variables or constants to the string, use \ () as follows:

let score = 80
let string = "My score is \(score) ."
// Print: My score is 80

This \ () method will be used frequently. Practice it and you will like it very much.   

Tuple tuple

Understanding difficulty
Practical degree

Tuple is a combination of multiple values into a composite value. The categories inside can be different. It is wrapped in a pair of parentheses (). Each value is separated by commas, as follows:

// Declare a tuple and fill in the value. The sequence is string, integer and floating point number
let personal data = ("Xiao Ming Wang", 28, 178.65)

// Get the third value of myInfo declared earlier, which is 2 because it starts from 0
let My height = personal data.2

// Print: My height is 178.25
print("My height \(My height)a centimeter")

// Decompose the previously declared myInfo into three constants
let (name, Age, weight) = personal data

// Print: My name is Kevin Chang
print("My name is \(name) .")

// Print: I am 25 years old  
print("I \(Age) Years old")

// If only some of these values are required, the unnecessary ones can be marked with a bottom line during decomposition

let (_, _, height) = personal data

// Print: My height is 178.25
print("My height \(height)a centimeter")

Each value in a tuple does not need to be of the same type.

More opportunities are to use the Array (Array) described below.

Tuple advantages:

  1. Tuples can store multiple types of elements at the same time, and the element type is fixed to ensure data security, unless you define the data type as Any. The compiler will check the assignment parameter type
  2. The number of elements of tuples is fixed and cannot be added or deleted. The compiler will strictly verify the number of assignment parameters

Array - array, array

Understanding difficulty
Practical degree

Array, array uses an ordered list to store multiple values of the same category. The same value can appear multiple times in different locations in an array.

There are two ways to declare array (array) variables or constants: array < Element > and [Element] (Element is a category that needs to be explicitly represented, such as Int, String, Double, etc.), as follows:

// Declare an array that stores Int classes
var arr: Array<Int>
var arr2: [Int]
// The two array category representations are functionally the same, so use the second one

// Declare an empty array with category Int
var arr3 = [Int]()

// At this time, if you want to assign this array as an empty array again
// Because the category has been defined when declared earlier
arr3 = []

// Or when a variable is declared for the first time with a clearly defined category, you can also use []
var anotherArr: [Int] = []

You can simply use [] to assign an empty array.

Fill in values directly to create an array (array)

You can also directly fill in values to create arrays (arrays). Each value is separated by commas, as follows:

var shoppingList: [String] = ["Eggs", "Milk"]
// That is, an array with a category of [String] and two values is created

var anotherList = ["Rice", "Apples"]
// Because the array contains values of category String
// Swift can infer that the category of this array is [String]

Swift will automatically infer the category, so if the value of the category is clearly expressed in the array, there is no need to label the category.  

Reading and modifying arrays

At the beginning, it was said that the array (array) is an ordered set, so the values in the array (array) can be obtained according to the index value (sequential sequence number), as follows: the index value of the array, that is, the first value is calculated from 0.

var My array = ["Apple", "egg", "milk", "rice", "water"]

// The index value of the array is calculated from 0, so arr4[2] refers to the third
// Want to print: milk
print(My array[2])

// To modify the value corresponding to an index value, you can directly assign it to a new value
 My array[2] = "orange"
// At this time, the milk has been changed into oranges, so it will print: oranges
print(My array[2])

// If you want to modify the value in an interval, you can use the interval writing method to modify it
 My array[1...4] = ["milk"]
// This will change the original index values 1 to 4 to milk
// So now my array will become ["apple", "milk"]
print(My array)

Think about it. What is the array printed out by "my array"?  

Arrays are mutable collections. They are very effective to create, but they must always be of a single type.

Dictionary - Dictionary

Understanding difficulty
Practical degree

A dictionary is used to store multiple values of the same category. Each value belongs to a unique key. The key is used as the identifier of the value in the dictionary. The categories of all keys must also be the same (the categories of keys and values do not have to be the same).

Because the values in the dictionary have no order, you need to find the required Value according to this Key. When declaring dictionary categories, use dictionary < Key, Value >, where Key represents the category of keys in the dictionary and Value represents the category stored in the dictionary, as follows:

// Declare a dictionary category
var someDict: Dictionary<String, String>

// Or it can be
var someAnotherDict: [String: String]

// Create an empty dictionary. If there are already category labels, you can set [:] as an empty dictionary, as follows:

// Declare that the category of an empty dictionary key is String and the category of value is Int
var My dictionary = [String: Int]()

// Add a value to the dictionary
 My dictionary["one"] = 1

// Then set the dictionary as an empty dictionary. Because there are already categories marked in front, use [:]  
My dictionary = [:]

ACCESS Dictionary

We can learn how to create, initialize and access dictionaries through the following examples:

var A dictionary:[Int:String] = [1:"One", 2:"Two", 3:"Three"]

var someVar = A dictionary[1]

print( "key = 1 The value of is \(someVar)" )
print( "key = 2 The value of is \(A dictionary[2])" )
print( "key = 3 The value of is \(A dictionary[3])" )

Think about it. What are the results of the above three prints?   

The above is the basic introduction of various data types.

In the future, we will explain more about how to apply, access and modify.

iOS development - learn Swift... After reading so many tutorials, do you understand? Swift is a powerful and easy to learn programming language such as iOS and macOS. Learning how to code swift can be simple and fun, and you can use it to build great applications! Here will explain the simple method and process of learning swift coding. Now is a good time to learn swift. After Swift 5, ABI is stable. If you like to learn more about the theory, go and find out what it means. In short, the stability of ABI shows that Swift is already a mature programming language. Otherwise, it is ridiculed by programmers, "since learning swift, I have to learn a new language every year". Swift 1,Swift 2,Swift 3,Swi.https://blog.csdn.net/weixin_42385177/article/details/121309969

Tags: Swift iOS Mac xcode

Posted on Wed, 17 Nov 2021 07:52:29 -0500 by Skepsis