Swift Basic Syntax
In the previous chapter, we already covered how to create a "Hello, World!" program in Swift. Now let's review it.\n\nIf you are creating an OS X playground, you need to import Cocoa:\n\n## Example\n\nimport Cocoa\n\n/* I'sFirst Swift Program */\n\n var myString ="Hello, World!"\n\nprint(myString)\n\nIf we want to create an iOS playground, we need to import UIKit:\n\n## Example\n\nimport UIKit\n\nvar myString ="Hello, World!"\n\n print(myString)\n\nExecuting the above program, the output result is:\n\nHello, World! \nThe above code represents the basic structure of a Swift program. Next, we will explain the components of the structure in detail.\n\n* * *\n\n## Swift Import\n\nWe can use the **import** statement to import any Objective-C framework (or C library) into a Swift program. For example, the **import cocoa** statement imports the Cocoa library and APIs, which we can then use in our Swift program.\n\nCocoa itself is written in Objective-C, and Objective-C is a strict superset of C, so we can easily mix C language code, and even C++ code, into Swift applications.\n\n* * *\n\n## Swift Tokens\n\nA Swift program consists of various tokens, which can be words, identifiers, constants, strings, or symbols. For example, the following Swift program consists of three tokens:\n\nprint("test!")\nThe above statement consists of 3 symbols: the word `print`, the symbols `( )`, and the string `"test"`.\n\nprint( "test!")\n\n* * *\n\n## Statements and Expressions\n\nCode in Swift consists of statements and expressions.\n\nStatements perform specific actions, while expressions compute and return values.\n\n## Example\n\nlet message ="Hello, Swift!"// Declaration statement\n\n print(message)// Expression statement\n\n// Expression example\n\n let sum =5+3// 5 + 3 Is an expression, returns 8\n\n let isGreater = sum >5// sum > 5 is an expression, returns true\n\n* * *\n\n## Comments\n\nSwift supports single-line comments and multi-line comments. Comments are used to explain the functionality and logic of the code.\n\nSwift's comments are very similar to those in C. Single-line comments begin with two forward slashes:\n\n// This is a single-line comment\nMulti-line comments start with `/*` and end with `*/`:\n\n/* This is also a comment, but spans multiple lines */\nUnlike C language multi-line comments, Swift's multi-line comments can be nested inside other multi-line comments. The syntax is to insert another multi-line comment inside one multi-line comment block. When the second comment block closes, it is still followed by the first comment block:\n\n/* This is the first multi-line comment'sStart /* This is nested'sSecond multi-line comment */This is the first multi-line comment'sEnd */\nNesting multi-line comments allows you to comment out code blocks more quickly and conveniently, even if the code block already contains comments.\n\n## Example\n\n// This is a single-line comment\n\n let age =25\n\n/*\n\n This is a multi-line comment\n\n Can span multiple lines\n\n Used to detail code functionality\n\n */\n\n let name ="Zhang San"\n\n// Comments can also be nested\n\n/*\n\n Outer comment\n\n /* Inner comment */\n\n Still Outer comment\n\n*/\n\n* * *\n\n## Semicolons\n\nUnlike other languages, Swift does not require a semicolon `;` at the end of each statement. However, when you write multiple statements on the same line, you must separate them with a semicolon:\n\n// Generally, semicolons are not required let x = 10let y = 20// Semicolons are required when writing multiple statements on the same line let a = 1; let b = 2; let c = 3// Can improve readability in some complex expressions let result = calculate(); process(result)\n\n* * *\n\n## Identifiers\n\nIdentifiers are names given to variables, constants, methods, functions, enums, structs, classes, protocols, etc.\n\nThe characters that make up an identifier follow certain conventions. The naming rules for identifiers in Swift are as follows:\n\n* Case-sensitive, `Myname` and `myname` are two different identifiers;\n* The first character of an identifier can start with an underscore `_` or a letter, but not a number;\n* Other characters in the identifier can be underscores `_`, letters, or numbers.\n\nFor example: `userName`, `User_Name`, `_sys_val`, `Height, etc.` are valid identifiers, while `2mail`, `room#`, and `class` are illegal identifiers.\n\n**Naming Conventions:**\n\n* Use camelCase\n* Variable and function names start with a lowercase letter\n* Type names start with an uppercase letter\n* Constants can use ALL_CAPS (separated by underscores)\n\n// Good'sNaming example let userAge = 25let maxRetryCount = 3let isUserLoggedIn = truelet serverURL = "https://api.example.com"// Avoid'sNaming example let a = 25 // Unclear meaning let temp = 3 // Unclear abbreviation let flag = true // Not specific let url1 = "..." // Numeric suffixes are bad\nBoolean naming:\n\n// Start with a question word let isEmpty = truelet isVisible = falselet hasChildren = truelet canEdit = falselet shouldRefresh = truelet willAppear = false\n> **Note:** The letters in Swift use Unicode encoding. Unicode, also known as the Universal Character Set, includes Asian character encodings such as Chinese, Japanese, Korean, and even the emoji characters we use in chat tools.\n> \n> \n> If you must use a keyword as an identifier, you can add backticks (\\`) around the keyword, for example:\n> \n> let `class` = "Tutorial"\n\n* * *\n\n## Constants and Variables\n\n### let and var Keywords\n\n**Constants (let):**\n\n// Declare constant let maximumNumberOfLoginAttempts = 10let welcomeMessage = "Welcome to Swift"// Constants cannot be changed once assigned // maximumNumberOfLoginAttempts = 5 // Error! Cannot modify constant // Lazily initialized constant let username: Stringif userIsLoggedIn { username = "User A"} else { username = "Guest"}// username Can only be assigned once\n**Variables (var):**\n\n// Declare variable var currentLoginAttempt = 0var friendlyWelcome = "Hello!"// Variable can modify currentLoginAttempt = 1 friendlyWelcome = "Bonjour!"// Variables can be assigned multiple times var temperature = 25.0 temperature = 30.0 temperature = 22.5\n\n* * *\n\n## Keywords\n\nKeywords are reserved character sequences similar to identifiers; they cannot be used as identifiers unless enclosed in backticks (\\`). Keywords are predefined reserved identifiers that have special meaning to the compiler.\n\nCommon keywords fall into the following 4 categories.\n\n### Declaration-related Keywords\n\nclass deinit enum extension\nfunc import init internal\nlet operator private protocol\npublic static struct subscript\ntypealias var\n\n### Statement-related Keywords\n\nbreak case continue default\ndo else fallthrough for\nif in return switch\nwhere while\n\n### Expression and Type Keywords\n\nas dynamicType false is\nnil self Self super\ntrue _COLUMN_ _FILE_ _FUNCTION_\n_LINE_\n\n### Keywords Used in Specific Contexts\n\nassociativity convenience dynamic didSet\nfinal get infix inout\nlazy left mutating none\nnonmutating optional override postfix\nprecedence prefix Protocol required\nright set Type unowned\nweak willSet\n\n* * *\n\n## Swift Whitespace\n\nThe Swift language does not completely ignore whitespace like C/C++ or Java. Swift has certain requirements for the use of whitespace, but it is not as strict about indentation as Python.\n\nIn Swift, an operator cannot directly follow a variable or constant. For example, the following code will report an error:\n\nlet a= 1 + 2\nThe error message is:\n\nerror: prefix/postfix '=' is reserved\nThis roughly means that the usage of an equal sign directly following or preceding something is reserved.\n\nThe following code will still report an error (continue to pay attention to whitespace):\n\nlet a = 1+ 2\nThe error message is:\n\nerror: consecutive statements on a line must be separated by ';'\nThis is because Swift considers the statement to end at `1+`, and `2` is treated as the next statement.\n\nOnly writing it this way will not cause an error:\n\nlet a = 1 + 2; // Coding standards recommend this style let b = 3+4 // This is also OK's\n\n* * *\n\n## Swift Literals\n\nA literal refers to a valueβsuch as a specific number, string, or booleanβthat directly expresses its type and assigns a value to a variable. For example, in the following:\n\n42 // Integer literal 3.14159 // Floating-point literal"Hello, world!" // String literal true // Boolean literal\n\n* * *\n\n## Print Output\n\nSwift uses the `print` function for output:\n\nprint("Tutorial") // Output Tutorial\nThe `print` function is a global function. Its complete function signature is:\n\npublic func print(items: Any..., separator: String = default, terminator: String = default)\nIf we want it to output without a newline, we just need to assign an empty string to the last parameter:\n\nfor x in 0...10{ print("\\(x) ", terminator: "")}print()\nThe output result is:\n\n0 1 2 3 4 5 6 7 8 9 10 \nIf you need to receive user input, you can use `readLine()`:\n\nlet theInput = readLine()
YouTip