Simplified version of swift basic syntax

2020-12-08 14:44:07

Recommend a learning website ：https://www.cnswift.org

The site is right Swift Translation of official documents , But it's not mindless translation , But combined with the author's development experience , On the basis of translation , Give some practical suggestions .

Constants and variables

stay Swift Specified in the , When defining an identifier, it must be made clear whether the identifier is a constant or a variable ：

Use let To define constants , It cannot be modified after definition ;

Use var To define variables , It can be modified after definition .

let a: Int = 2a = 3// Will report a mistake , because a Is a constant , Cannot be modified
var b: Int = 6b = 8// The normal operation ,b It's a variable. , You can modify

Basic data type

Swift The basic data types in include ： integer 、 floating-point 、Bool type

integer

signed int

Int8： A signed 8 An integer

Int16： A signed 16 An integer

Int32： A signed 32 An integer

Int64： A signed 64 An integer

Int： Default , Platform related , amount to OC Medium NSInteger

Unsigned integer

UInt8： Unsigned 8 An integer

UInt16： Unsigned 16 An integer

UInt32： Unsigned 32 An integer

UInt64： Unsigned 64 An integer

UInt： Default , Platform related , amount to OC Medium NSUInteger

floating-point

Float：32 Bit floating point type

Double：64 Bit floating point type （ Default ）

Bool type

true： really

false： false

The operation of basic data type and OC It's the same ：

a-b// reduce
a*b// ride
a/b// except
a%b// Remainder

a+b// Add a-b// reduce a*b// ride a/b// except a%b// Take the surplus, but it should be noted that , stay Swift in , Different types of data are not computable , For example, integers and floating-point types can't be operated together ： If you want to calculate , So you have to convert one type to another ：

var c = 1var d = 1.1Double(c)+d

Swift Type derivation in

Swift Is a strong type of language , in other words , stay Swift in , Any variable or constant must have a definite type .

var d: Int = 8

If there is a direct assignment when defining an identifier , After the identifier The type of can be omitted ：

var d = 8

because Swift Categorical derivation , It will automatically determine the data type of the previous identifier according to the following assignment .

We can go through option+ Left mouse button to view the data type of the variable ： It should be noted that , If the type of a variable has been determined , Then you can't assign another type of value to a variable ： The variables here c It's an integer , Then it can only be assigned an integer value , Cannot assign other types of values .

Operator

Calculation operator

+、-、*、/、%

Here's the thing to watch out for , The data types on both sides of the calculation operator must be of the same type , If the type is different , The compiler will report an error .

Assignment operator

=、+=、-=、*=、/=、%=

Here's the thing to watch out for , The data types on both sides of the assignment operator must be of the same type , If the type is different , The compiler will report an error .

Comparison operator

、>=、<、<=、==、!=

Here's the thing to watch out for , The data types on both sides of the comparison operator must be of the same type , If the type is different , The compiler will report an error .

Interval operator

Swift Peculiar .

1...8   // Closed interval operators , From 1 To 8（ Include 1 and 8） The interval of all the values of 1...    // Closed interval operators , From 1 Extend back to infinity ...8    // Closed interval operators , From 8 It's going forward, infinitely 1..<8   // Semi open interval operator , From 1 To 8（ Include 1, But not including 8） The interval of all the values of ..<8    // Semi open interval operator , From 8 forward （ barring 8） Infinite extension

Tuples

OC There is no tuple type in , A tuple is Swift A data structure unique to .

Tuples are used to define a set of data , The data that makes up a tuple can be called an element .

We now use tuples to describe a person's information ：

var one = ("Norman", "male", 30, 178.5)print(one.0)

And hold it down option Key click , Find variables one Of the following types ： This type is derived from the value of the assignment .

Tuple above one From left to right, the element in represents ： name 、 Gender 、 Age 、 height . People at first glance , In fact, I still don't know the meaning of each element , So just for the sake of understanding , In order to be able to see the meaning of the text , We can also define tuples like this ：

// Name the element in the tuple , You can then access the element by its name
var one = (name:"Norman", gender:"male", age:30, height:178.5)
print(one.name)

Hold on option Key click , Find variables one Of the following types ： // Writing a
// The subscript access
print(error.0)
print(error.1)

// Write two
// Alias access
print(error.errorCode)
print(error.errorInfo)

The branch of logic

Introduction to branches

So called branch statement , Namely if/switch/ Judgment statements such as ternary operators .

The execution process of a program can be controlled by branch statements .

if Branch statement

Swift Medium if Statement and OC Medium if There is still a difference between the statements ：

difference 1：Swift There is no parenthesis in the middle judgment sentence (), But the execution statement after judgment must use curly braces {} Cover up ;OC The judgment sentence in Chinese must be enclosed in parentheses (), If there is only one sentence after the judgment, the curly bracket can be omitted {}.

let g = 8if g>0 {    print(" Positive numbers ")}

difference 2：Swift There must be a definite truth or falsehood in the judgment sentence of , There must be a definite Boolean value ,Swift There is no more wrong in 0 The concept of truth ;OC Right and wrong 0 be appointed after a period as acting 、 Non empty is true . Ternary operator

Swift The binocular operation and OC In a consistent style .

let a = 10;let b = 20;
// Print larger values print(a > b ? a : b);

guard Use

guard Statements and if The statement is very similar , But with the if The difference is ,guard Statement when the condition is false Only when {} Code inside .

guard Statement must have else sentence , His grammar is as follows ：

• When the conditional expression is true I'll skip else The content of the statement , Execute the following statement group ;
• When the conditional expression is false When it comes to execution else What's in the sentence , Jump statements are usually return、break、continue perhaps throw
guard  Conditional expression  else {  // The statement executed when the conditional expression does not hold   break}
Statement group

Another point to note is that ,guard Statement must be placed in a function .

func online(age : Int) -> Void {    guard age >= 18 else {        print(" Minors are not allowed to access the Internet ")        return    }    print(" You can go online ")}
online(age: 17)

Switch-case sentence

switch As an essential part of the choice statement, it has also been added to Swift in .

/** case Section */let a = 100
switch a {case ..<60:    print(" fail, ")case 60..<80:    print(" qualified ")case 80..<90:    print(" good ")case 90...100:    print(" good ")default:    print(" genius ")}
/**  One case Multiple values can be judged , Multiple values to , separate */let b = 0
switch b {case 0,1:    print(" normal person ")default:    print(" other ")}
/** fallthrough Keywords for penetration *  The so-called penetration is , When this case When you are satisfied , Finish this case After the corresponding content ,*  Will not jump out of , It's followed by the next one case Corresponding content */let c = 0
switch c {case 0:    fallthroughcase 1:    print(" normal person ")default:    print(" other ")}
/** switch It supports multiple data types *  It not only supports integers 、 Section , Floating point is also supported 、 String, etc. .*/let d = 10let e = 5var result = 0
let opration = "+"
switch opration {case "+":    result = d + ecase "-":    result = d - ecase "*":    result = d * ecase "/":    result = d / edefault:    result = 0}

Swift Medium case The following statement block can be executed without following break, Because by default, there will be break.

loop

stay C/OC in , Common cycles are for/while/do-while; stay Swift in , The corresponding cycles are for/while/repeat-while.

For loop

for There are two types of cycles , One is traditional C stylistic for loop , as follows ：

for var i = 0; i < 10; i++ {    print(i)}

This traditional way of writing , stay Swift3 China has been eliminated , as follows ： The other is for-in loop , as follows ：

for i in 0..<10 {    print(i)}

About for-in loop , There is a special place to pay attention to ： If you don't need a subscript in a loop i, So use the underline instead of the subscript , As shown below ：

for _ in 0..<10 {    print("Swift")}

Otherwise, there will be the following warning ️： while Circulation and repeat-while loop

//while loop （ First judge , Re execution ）var a = 0
while a < 10 {    print(a)    a+=1}
//repeat-while loop （ Do it first , To determine ）var a = 0
repeat {    print(a)    a += 1} while a < 0

Swift Medium repeat-while Circulation and OC Medium do-while The cycle is as like as two peas. , Can be guaranteed to be executed at least once .

character string

OC and Swift There is a difference between strings in ：

• stay OC in , The string type is NSString; stay Swift in , The string type is String.
• OC To define a string in is to use @"";Swift To define a string in is to use "".

Definition of string

// Immutable string let str1 = " Immutable string "
// Variable string var str2 = " Variable string "str2 = " I change "
// Multiline string var str3 = """ Multi line string first line second line third line fourth line 56"""

Several traditional string definition forms are introduced above , Now let's talk about it Swift5.0 After the launch of the new Raw String（ Original string ）.

Raw String It's using # To wrap strings , Its biggest characteristic is ： it There is no special escape processing for backslashes .

When a string contains double quotes or backslash escape characters , In the traditional way, it is defined as follows ：

let var1 = " If there are double quotation marks in the sentence "" It would be embarrassing "// Output ： If there are double quotation marks in the sentence "" It would be embarrassing let var2 = " If there is an escape character in the sentence, it will be embarrassing "// Output ： If there is an escape character in the sentence, it will be embarrassing

Use Swift5.0 The new RawString The definition is as follows ：

let var1 = #" If there are double quotation marks in the sentence "" It would be embarrassing "#let var2 = #" If there is an escape character in the sentence, it will be embarrassing "#

If the string is # The parcel , that There is no need to escape .

If there is a #, Then what shall I do? ？ The answer is to use two pound marks ## To the parcel ：

let var1 = ##" If there is a pound sign in the sentence #"##// Print the results ： If there is a pound sign in the sentence #

Common operation of string

// Calculate the length of the string
let str = "12345678"
print(str.count)
print((str as NSString).length)

// Concatenate two strings
var str1 = "Norman" + "Lee"
var str2 = str1.appending("666")

// Traversal string （ A string can be seen as a collection of multiple characters ）
let str = "abcdefg"
for char in str {
print(char)
}

// Whether the string contains a substring
let str = "abcdefg"
print(str.contains("abc")) //true
print(str.contains("A")) //false
print(str.contains("h")) //false

// Split string
let str = "abc&def&ghi&jkl&mn"
let desc = str.components(separatedBy: "&") // ["abc", "def", "ghi", "jkl", "mn"]
for item in desc {
print(item)
}

// String substitution
let str = "abc&def&ghi&jkl&mn"
let result = str.replacingOccurrences(of: "&", with: "---")
print(result) // abc---def---ghi---jkl---mn

Array

Arrays are a bunch Orderly By Elements of the same type Composed of aggregate .

The elements in the array are ordered , Can be repeated .

Swift use Array Represents an array , It's a Generic set .

Initialization of an array

The array is divided into Variable and immutable arrays

// Define a variable array
var arrar1 : [String] = [String]() // In this case, an empty array is defined

// Define an immutable array
let array2 : [String] = ["Norman", "Lavie"]

Make a statement Array There are two ways to write types , You can choose either ：

// Grammatical sugar var array1 : [String]
var array2 : Array<String>

The declared array needs to be initialized before it can be used , Array types are often initialized at the same time as they are declared ：

// Define and initialize directly at the same time
var array1 = ["Norman", "Lavie"]

// First define , Then initialize
var array2 : Array<String> array2 = ["Norman", "Lavie"]

Pay attention to distinguish between <u > Arrays and tuples </u>.

Basic operations of arrays

var array = ["Norman", "Lavie", " The rain becomes the LAN "]

// To obtain the length of the
array.count // 3

// Sentenced to empty
array.isEmpty // false

// Add elements to the end
array.append(" Big fish ") // ["Norman", "Lavie", " The rain becomes the LAN ", " Big fish "]

// Inserts the element at the specified location
array.insert("Bruce", at: 1) // ["Norman", "Bruce", "Lavie", " The rain becomes the LAN ", " Big fish "]

// Remove elements
array.remove(at: 0)
array.removeLast()
array.removeFirst()

// Modifying elements
array = " petty thief "

// Value （ The value is obtained directly through the subscript index ）
print(array)
print(array)

// In reverse order
array.reverse()

Traversal of array

var array = ["Norman", "Lavie", " The rain becomes the LAN ", " Big fish "]

//for-in Ergodic subscript
for i in 0..<array.count {
print(array[i])
}

//for-in Traversing elements
for name in array {
print(name)
}

// Traversing elements in an interval
for name in array[0...2] {
[print(name)]
}

// Traversal of tuple mode ( If you need to get both the index and the element , This method is recommended )
for (index, name) in array.enumerated() {
print(index)
print(name)
}

Merging of arrays

var array1 = ["Norman", "Lavie"]
var array2 = [" The rain becomes the LAN ", " Big fish "]
array1 += array2
print(array1) // ["Norman", "Lavie", " The rain becomes the LAN ", " Big fish "]

Although only a plus sign can be used to merge arrays , But make sure that ： Of two or more arrays to merge Element types must be consistent .

Dictionaries

Dictionaries are written by Key value pair （key:value） Set of components , It consists of a set of two parts ： One is the key set , One is a collection of values . Dictionaries access values indirectly through access keys , There can be no duplicate elements in the key set , The elements in the value set are repeatable .

The elements in the dictionary are disorder Of .

Swift The dictionary type in is Dictionary, It's a Generic set .

Initialization of a dictionary

stay Swift in , Use let A modified dictionary is an immutable dictionary , Use var A modified dictionary is a variable dictionary ：

// Defining a variable dictionary
var dic1 : [String : Any] = [String : Any]()

// Define an immutable Dictionary
let dic2 : [String : Any] = ["name" : "Norman", "age" : 28]

When declaring a dictionary , There are two ways , You can choose either ：

var dic : [String : Any]
var dic : Dictionary<String, Any>

Like an array , The declared dictionary also needs to be initialized before it can be used ：

// Initialize while declaring
var dic1 : [String : Any] = [String : Any]()

// First of all , Post initialization
var dic : Dictionary<String, Any>
dic = ["name" : "Norman", "age" : 28]

Say something extra , stay Swift in , Any type is used Any To express Of .

Basic operation of dictionary

var dict : [String : Any] = ["name" : "Lavie", "age" : 18, "gender" : "male"]

// length
print(dict.count)

// Sentenced to empty
print(dict.isEmpty)

dict["height"] = 178
dict["weight"] = 65

/*
*  It should be noted that , The way you add elements to it , If Key Value does not exist , So add elements ;
*  If Key The value is , So it's modifying elements
*/

// Remove elements
dict.removeValue(forKey: "age") //  Deletes the specified element
dict.removeAll() //  Delete all elements

// Revise the dictionary
dict["name"] = "Norman" //  Mode one
dict.updateValue(" Big fish ", forKey: "name") //  Mode two

// Look up the dictionary
print(dict["name"])

Traversal of dictionaries

var dict : [String : Any] = ["name" : "Lavie", "age" : 18, "gender" : "male"]

// Traverse all the Value value
for value in dict.values {
print(value)
}

// Traverse all the Key value
for key in dict.keys {
print(key)
}

// Traverse all key value pairs
for (key, value) in dict {
print(key)
print(value)
}

Dictionary merging

The previous string and array , You can use the plus sign directly + To merge , But that doesn't apply to dictionaries . You can't use the plus sign directly in a dictionary + To merge . Dictionaries should be merged in the following ways ：

var dict1 : [String : Any] = ["name" : "Lavie", "age" : 18, "gender" : "male"]var dict2 : [String : Any] = ["height" : 178, "weight" : 65]for (key, value) in dict2 {    dict1[key] = value}print(dict1) // ["gender": "male", "age": 18, "weight": 65, "height": 178, "name": "Lavie"]

But this way of merging dictionaries requires special attention , If there is Key The nuptial , Then the Key In the original dictionary Value The value will be the corresponding in the new dictionary Value Value override .

Optional

stay OC in , If a variable is not used for the time being , It can be assigned to 0（ Basic data type ） Or assign it to nil（ object type ）. stay OC in ,nil It means a null pointer , It's not as a special type .

stay Swift in ,nil It's a special type , It is associated with Int、String equally , It's all one type . also Swift Language is a strongly typed language , Therefore, it is not possible to directly nil Assign values to other types of data .

In development , meet nil Be unavoidable , therefore Swift Optional types are available .

The values of the optional types are as follows ：

• Without value ——nil
• When there is value —— Normal value

Define optional types

// Writing a ： Official definition
var a : Optional<Int> = 6 //  Valuable
a = nil // nil

// Write two ： Grammatical sugar （ Just put a question mark after the type ?）
var b : Int? = 8 //  Valuable
b = nil // nil

Use of optional types

Assign values to optional types :

//  Define optional types
var name : String? = nil

// Assign values to optional types
name = 123 //  Wrong writing , Optional types also have type checking , Only strings can be copied here , Assigning other types will report errors
name = "norman" //  correct

//  Print the results
print(name) // Optional("norman")   Because it's an optional type , So they will bring Optional

Take the value of an optional type （ Explicit unpacking ）：

//  Define optional types
var name : String? = "Norman"

print(name) // Optional("norman")

// Take out the true value of the optional type
// Use ！ Compulsory unpacking （ Explicit unpacking ）
print(name!) // Norman

// If the optional type is nil, Force unpacking will cause errors
name = nil
//print(name!) //  Report errors ：Unexpectedly found nil while unwrapping an Optional value

// The correct way to write should first judge empty
if name != nil {
print(name!)
}

Take the value of an optional type （ Implicit unpacking ）：

Swift There is one of them. if-let How to write it ,if-let It's for optional binding （ Implicit unpacking ） Of , as follows ：

if let  Constant  =  Optional  {    // Processing constants }

there 【 Constant = Optional 】 The function of a sentence is ： If the optional value is not nil, Then pass the optional true value to the constant , And execute curly braces {} The words in it ; If the optional value is nil, that 【 Constant = Optional 】 This condition does not hold （ Because you can't directly assign a non optional variable to nil）, Then you won't go to the content in curly braces .

//  Define optional types
var name : String? = "Norman"

/*
* Optional binding （ Implicit unpacking ）
*/
if let nameString = name {
print(nameString)
}

It is highly recommended to use optional binding to implicitly unpack the optional selection

Type conversion

Basic data type conversion

such as Double turn Int,Int turn Float etc. , Just use the data type ( Type to be transferred ) that will do ：

//Int turn Double
var a : Int = 6
var b : Double = Double(a)

//Float turn Int
var c : Float = 8.99
var d : Int = Int(c)

Basic types and string conversions

// String interpolation can directly convert the underlying type to a string
var age : Int = 6
var str = " Xiaoming this year (age) Year old "

// String to basic type , You have to make sure that the contents of the string are convertible
var string = "123"
var d = Int(string)

function

Swift The function in , It's the same thing as Objective-C The method in . The format of the function is as follows ：

func  Function name ( Parameters , list )  ->  return type  {     Code block     return  Return value }

Here are some instructions ：

1,func Is the key to define a function

2, Between multiple parameters in the parameter list , You can use English commas , Division , There can be no parameters

3, Use -> Point to the return value type

4, If the function does not return a value , be -> return type Part can be omitted

Common function types

No parameters , no return value ：

// Writing a ： Official standard writing
func drinkWater() -> Void {
print("drink water 111")
}

// Write two ： If there is no return value ,Void It can be written. ()
func drinkWater1() -> () {
print("drink water 222")
}

// Write three ： If there is no return value , The following content can be left blank
func drinkWater2() {
print("drink water 333")
}

// Call function
drinkWater()
drinkWater1()
drinkWater2()

With parameters , no return value ：

func call(phoneNumber : String) {    print(" Join in iOS Communication group (phoneNumber)")}call(phoneNumber: "642363427")

No parameters , There is a return value ：

func myName() -> String {    return "norman"}let name = myName()

With parameters , There is a return value ：

func plus(a : Int, b : Int) -> Int {    return a + b;}let result = plus(a: 3, b: 3)

Attention to the use of functions

1, The formal parameter of each function contains two parts: formal parameter label and formal parameter name

• Formal parameter tags are used when calling functions
• Formal parameter names are used in the implementation of functions
• When the function is called , Each formal parameter is preceded by a formal parameter label
• By default , Formal parameters use their formal parameter names as formal parameter labels
• If you don't want a formal parameter tag , You can add... Before the formal parameter name _
// there info1 and info2 It's the formal parameter tag
//name and age Is the formal parameter name
func personalInfo(info1 name : String, info2 age : Int) {
// Use formal parameter names in the implementation of functions
print(" full name ：(name), Age ：(age)")
}
// Use formal parameter tags when calling functions
personalInfo(info1: "norman", info2: 23)

// Here's the default
// here ,name and age It's a formal parameter tag , It's also a formal parameter name
func personalInfo(name : String, age : Int) {
// When implemented inside a function ,name and age Is the formal parameter name
print(" full name ：(name), Age ：(age)")
}
// When a function is called ,name and age It's a formal parameter tag
personalInfo(name: "norman", age: 24)

// If you don't want a formal parameter tag , You can add... Before the formal parameter name  _
func personalInfo(_ name : String, _ age : Int) {
print(" full name ：(name), Age ：(age)")
}
// When a function is called , No formal parameter tag
personalInfo("norman", 24)

2, You can set default values for the parameters of a function

// If you don't want a formal parameter tag , You can add... Before the formal parameter name  _
func personalInfo(_ name : String = "lavie", _ age : Int = 28) {
print(" full name ：(name), Age ：(age)")
}

personalInfo() //  full name ：lavie, Age ：28
personalInfo("norman", 24) //  full name ：norman, Age ：24

3, Pointer passing

By default , The argument to a function is value passing . If you want to change the variables outside , You need to pass the address of the variable .

// Exchange value
func swapInt(a : inout Int, b : inout Int) {
let temp = a
a = b
b = temp
}

var a = 6
var b = 8
print("a=(a), b=(b)") // a=6, b=8
swap(&a, &b) //  Pass the address in
print("a=(a), b=(b)") // a=8, b=6

Type of function

The array we introduced earlier Array、 Dictionaries Dictionary etc. , All are Value type , And the function is Reference type .

Each function has its own type , The type of a function is determined by the function's Parameter type and Return type Decisive .

With function types , You can take a function type like Int、Array It's the same thing to use .

The following example defines additionMethod and multiplicationMethod Two functions , Both of these functions pass in two Int Parameters of type , Return to one Int Type values , So the type of both functions is (Int, Int) -> Int

func additionMethod(a : Int, b : Int) -> Int {    return a + b;}
func multiplicationMethod(a : Int, b : Int) -> Int {    return a * b;}

Let's take a look at the simple assignment of functions ：

// Initialize a function type variable , And initial value
mathMethod(2, 3) // 5
// Assign other values to function type variables
mathMethod = multiplicationMethod
mathMethod(2, 3) // 6

A function can also be used as an argument to a function ：

func additionMethod(a : Int, b : Int) -> Int {
return a + b;
}

func multiplicationMethod(a : Int, b : Int) -> Int {
return a * b;
}

// Function as parameter
func printResult(a : Int, b : Int, mathMethod : (Int, Int) -> Int) {
print(mathMethod(a, b))
}

printResult(a: 3, b: 4, mathMethod: additionMethod) // 7
printResult(a: 3, b: 4, mathMethod: multiplicationMethod) // 12

Function can also be used as the return value of a function ：

func additionMethod(a : Int, b : Int) -> Int {
return a + b;
}

func multiplicationMethod(a : Int, b : Int) -> Int {
return a * b;
}

// Function as return value
func mathMethod(a : Int) -> (Int, Int)->Int {
if a > 10 {
}
return multiplicationMethod
}

var resultMethod = mathMethod(a: 11)
resultMethod(6, 8) // 14

Recommended articles

https://chowdera.com/2020/12/20201208144338707w.html