If you’re used to OC’s syntax, you might be a little resistant to Swift’s syntax for the first time, because Swift’s syntax is a bit weird. However, if you have a basic knowledge of the front end, learning Swift may be a bit of a struggle, and if you have a basic knowledge of C++ it may be faster. No matter what grammar background you have, Swift is a great language to learn. It’s much simpler and more efficient than OC. Now that the Swift ABI is 5.2, the overall stability and active community make it a good time to learn from the system.

I. Print

Can be considered an extension of C:

let word = "world"

print("print output"// Output:print output

print("hello \(word)") // Output: Hello world

Copy the code
  • Used to print variables in OCNSLog("hello_%@",var)Use, Swift\ (variable)

Second, the semicolon

  • A semicolon can be omitted at the end of a line of code.;)
  • Multiple lines of code must be written on the same line with a semicolon (;)

Three, comments,

  • Single-line comment (//)
  • Multi-line comments — Multi-line nesting is supported, but must be double-labeled (/**/)
// Single-line comment



/ *

Multiline comment

* /



/ *

1. Multi-line comments

/* Multi-line comment nesting */

2. Multi-line comments

* /

Copy the code

Markup syntax is supported by comments on Playground (similar to markdown).

  • Check the current line -> Menu bar -> Editor -> Show Rendered Markup
  • Go to Render: Show Rendered Markup
  • Close render: Show Raw Markup
  • Note: Markup syntax is valid only on Playground

Markup syntax

/ / :# Level 1 title

/ / :## Secondary title



/ * :

 # Level 1 title

 

 ## Unordered list

- The first element

- Second element

 

 ## Ordered list

1. First element

2. Second element

 

 # # notes

< p style = "max-width: 100%; clear: both; min-height: 1em



 # # line

 ---

 

 # # image

! [Image description](Link to image)

 

 # # link

[Link title](link address)

 

 ## Bold/italic

This is ** bold **, this is ** italic *

* /

Copy the code

  • Single-line comments cannot be preceded by a space, but must be followed by a space
  • In a multi-line comment, a colon must start on a new line

Identifiers

  • Identifiers (such as constant names, variable names, function names) can use almost any character
  • The identifier cannot start with a number and cannot contain special characters such as whitespace characters, Tab characters, and arrows

6. Data types

Swift has no concept of basic data types, which fall into two broad categories:

6.1. Value type (value-type)

  • Enumeration (enum)
    • Optional
  • Structure (struct)
    • Bool, Int, Float, Double, Character
    • String, Array, Dictionary, Set

6.1.1. Integer type

  • Int8, Int16, Int32, Int64, UInt8, UInt16, UInt32, UInt64
  • On 32-bit platforms, Int is equivalent to Int32; On 64-bit platforms, Int is equivalent to Int64. In general, Int should be used directly, unless there are strict internal requirements.
  • Uint8.max, int16.min

6.1.2. Floating point types

  • Float, 32 bits, precision is only 6 bits
  • Double, 64 bits, accuracy at least 15 bits

Also 6.1.3. Literal

  • Boolean values in OC are0and1But Swift doestrueandfalse(Like most languages)
  • String values are quoted in double quotes
  • Character type values are enclosed in double quotes as strings, but character variables must beCharacterModifier, otherwise it defaults to a string
/ / / a Boolean

let bool = true



/ / string

let string = "1024 star"



/ / character

let character: Character = "🌎"



/ / integer

let intDecimal = 20

let intBinary = 0b10001

let intOctal = 0o21

let intHexDecimal = 0x11



/ / floating point number

letDoubleDecimal = 125.0 // decimal, equivalent to 1.25e2, for example: 0.0125 <=> 1.25E-2



letDoubleHexDecimal1 = 0xFp2 // In hexadecimal, meaning 15x2^2, equivalent to 60.0 in decimal



letDoubleHexDecimal2 = 0xfP-2 // in hexadecimal, meaning 15x2^-2, equivalent to 3.75 in decimal



/* 12.1875

Decimal notation: 12.1875, 1.21875E1

Hex: 0xc.3P0

* /



/ / array

let array = [1, 2, 3, 4, 5]



/ / a dictionary

let dictionary = ["age": 20."height" : 1.88]



Copy the code
  • Integers and floating-point numbers can be added with extra zeros or underlined to improve readability
    • 100_0000, 1_000_000.000_000_1, 000123.456

6.2. Reference Type

  • Class (class) As you can see from the official introduction, Int is described by struct

Type conversion

7.1. Integer conversion

Operations between different types cannot be performed in Swift, otherwise the compiler will report an error

Do it right:

let int1: UInt16 = 2_000

let int2: UInt8 = 1

let int3 = int1 + UInt16(int2)

Copy the code
  • Convert a low type to a high type (why? Byte occupancy)

7.2. Integer and floating point conversion

let int1: UInt16 = 2_000

let int2: UInt8 = 1

let int3 = int1 + UInt16(int2)



let int = 3

letDouble = 0.1415926

let pi = Double(int) + double

print// Output: 3.1415926

let intPi = int + Int(double)

print(intPi) // Output: 3

Copy the code
  • Floating-point conversion is to discard the decimal point and take only the part of the integer

Consider: conversion is needed every time, what about unknown types of data (data returned by the server)?

// Literals can be added directly, because numeric literals themselves have no explicit type

letResult = 3 + 0.1415926

print(result) // Output: 3.1415926

Copy the code

Var and let

  • Let for constant, var for variable (short for variable)
  • The compiler can automatically infer the type of a variable/constant
  • Both must be initialized before use (unlike in other languages, initialization is not required during compilation), otherwise an error will be reported during compilation

Format:

letVariable name: Variable type = variable value;



Var Variable name: variable type = variable value;

Copy the code

The sample

let age: Int = 10;

print(age) // Output: 10



var name: String = "idbeny";

print(name) // Output: idbeny

Copy the code

Nine, yuan group

Tuples are concepts borrowed from C++ (Python also has this type) :

  • Tuples are similar to lists except that the elements of a tuple cannot be modified.
  • Tuples use parentheses and lists use square brackets.
  • Tuple creation is as simple as adding elements in parentheses, separated by commas (infinite).
  • When using tuple deconstruction, the variable name must not conflict with other generally-defined variables in the same scope

Format:

/ *

Format 1: General

Read format: variable name. The index

* /

Variable name = (element value, separated by multiple commas)



/ *

Format 2: Deconstruction

Variable modifier (the name of the variable corresponding to the tuple value, the position must be one-to-one) = defined tuple variable

Read format: variable name

* /

Variable modifier (the name of the variable corresponding to the tuple value, the position must be one-to-one) = defined tuple variable



// Deconstruct the extension: underline the corresponding position when it is not needed

Variable modifier (variable name corresponding to tuple value, _) = defined tuple variable



/ *

Format 3: key-value

Read format: 1. Variable name. Index 2. Variable name. Element variable name

* /

Variable modifier Variable name = (element variable name: element value...)

Copy the code

Example:

let tup1 = (404, "Not Found"."moreParas")

print404 Not Found moreParas (tup1.0,tup1.1,tup1.2



let (statusCode, statusDesc, paras) = tup1

print(statusCode, statusDesc, paras



let (tempStatusCode, _, _) = tup1

print(tempStatusCode) // Output: 404



let httpStatus = (statusCode: 404, statusDesc: "Not Found", paras: "moreParas")

printStatusCode, httpstatusdesc, httpstatus.paras) // 404 Not Found moreParas

Copy the code