Swift Basic Syntax
In the previous chapter, we already discussed how to create the "Hello, World!" program in Swift. Now let's review it.
If you are creating an OS X playground, you need to import Cocoa:
Example
/* My first Swift program */
var myString = "Hello, World!"
print(myString)
If we want to create an iOS playground, we need to import UIKit:
Example
var myString = "Hello, World!"
print(myString)
Execute the above program, and the output result is:
Hello, World!
The above code is the basic structure of a Swift program. Next, we will explain the components of the structure in detail.
Swift Import
We can use theimportstatement to import any Objective-C framework (or C library) into a Swift program. For exampleimport cocoaThe statement imports the Cocoa library and APIs, and we can use them in Swift programs.
Cocoa itself is written in Objective-C, and Objective-C is a strict superset of C, so in Swift applications we can easily mix in C language code, and even C++ code.
Swift Tokens
A Swift program is composed of various tokens. Tokens can be words, identifiers, constants, strings, or symbols. For example, the following Swift program consists of three tokens:
print("test!")
The above statement consists of 3 symbols: the wordprint, the symbol( ), and the string"test"。
print ( "test!" )
Statements and Expressions
Code in Swift consists of statements and expressions.
Statements perform specific actions, while expressions evaluate and return values.
Example
print(message) // Expression statement
// Expression example
let sum = 5 + 3 // 5 + 3 is an expression, returns 8
let isGreater = sum > 5 // sum > 5 is an expression, returns true
Comments
Swift supports single-line comments and multi-line comments. Comments are used to explain the functionality and logic of code.
Swift comments are very similar to C language. Single-line comments start with two forward slashes:
// This is a line comment
Multi-line comments start with /* and end with */:
/* This is also a comment, but it spans multiple lines */
Unlike C language multi-line comments, Swift's multi-line comments can be nested inside other multi-line comments. The way to write it is to insert another multi-line comment within a multi-line comment block. When the second comment block closes, the first comment block still continues:
/* This is the beginning of the first multi-line comment /* This is the nested second multi-line comment */ This is the end of the first multi-line comment */
Nesting multi-line comments allows you to annotate code blocks more quickly and conveniently, even if the code block already contains comments.
Example
let age = 25
/*
This is a multi-line comment
Can span multiple lines
Used to explain code functionality in detail
*/
let name = "Zhang San"
// Comments can also be nested
/*
Outer comment
/* Inner comment */
Still the outer comment
*/
Semicolon
Unlike other languages, Swift does not require a semicolon at the end of each statement.;But when you write multiple statements on the same line, you must separate them with semicolons:
// 一般情况下不需要分号 let x = 10 let y = 20 // 在同一行写多个语句时需要分号 let a = 1; let b = 2; let c = 3 // 在某些复杂表达式中可以提高可读性 let result = calculate(); process(result)
Identifiers
Identifiers are names given to variables, constants, methods, functions, enums, structs, classes, protocols, and so on.
The letters that make up an identifier must follow certain rules. The naming rules for identifiers in Swift are as follows:
- Case-sensitive: Myname and myname are two different identifiers;
- The first character of an identifier can be an underscore_or a letter, but cannot be a number;
- Other characters in the identifier can be underscores_, letters, or numbers.
For example: userName, User_Name, _sys_val, height, etc. are valid identifiers, while 2mail, room#, and class are invalid identifiers.
Naming conventions:
- Use camelCase.
- Variable and function names start with a lowercase letter.
- Type names start with an uppercase letter.
- Constants can be all uppercase (separated by underscores).
// 好的命名示例 let userAge = 25 let maxRetryCount = 3 let isUserLoggedIn = true let serverURL = "https://api.example.com" // 避免的命名示例 let a = 25 // 不清楚含义 let temp = 3 // 缩写不明确 let flag = true // 不具体 let url1 = "..." // 数字后缀不好
Boolean naming:
// 使用疑问词开头 let isEmpty = true let isVisible = false let hasChildren = true let canEdit = false let shouldRefresh = true let willAppear = false
Note:The letters in Swift use Unicode encoding. Unicode is called the unified encoding system. It includes Asian character encodings, such as Chinese, Japanese, Korean, and even emojis we use in chat tools.
If you insist on using a keyword as an identifier, you can add backticks around the keyword`, for example:
let `class` = "Example"
Constants and Variables
let and var keywords
Constants (let):
// 声明常量
let maximumNumberOfLoginAttempts = 10
let welcomeMessage = "欢迎使用Swift"
// 常量一旦赋值就不能更改
// maximumNumberOfLoginAttempts = 5 // 错误!不能修改常量
// 延迟初始化常量
let username: String
if userIsLoggedIn {
username = "用户A"
} else {
username = "访客"
}
// username 只能赋值一次
Variables (var):
// 声明变量 var currentLoginAttempt = 0 var friendlyWelcome = "Hello!" // 变量可以修改 currentLoginAttempt = 1 friendlyWelcome = "Bonjour!" // 变量可以多次赋值 var temperature = 25.0 temperature = 30.0 temperature = 22.5
Keywords
Keywords are reserved character sequences similar to identifiers. Unless enclosed with backticks`, they cannot be used as identifiers. Keywords are predefined reserved identifiers that have special meaning to the compiler.
There are 4 common types of keywords.
Keywords related to declarations
| class | deinit | enum | extension |
| func | import | init | internal |
| let | operator | private | protocol |
| public | static | struct | subscript |
| typealias | var |
Keywords related to statements
| break | case | continue | default |
| do | else | fallthrough | for |
| if | in | return | switch |
| where | while |
Expression and type keywords
| as | dynamicType | false | is |
| nil | self | Self | super |
| true | _COLUMN_ | _FILE_ | _FUNCTION_ |
| _LINE_ |
Keywords used in specific contexts
| associativity | convenience | dynamic | didSet |
| final | get | infix | inout |
| lazy | left | mutating | none |
| nonmutating | optional | override | postfix |
| precedence | prefix | Protocol | required |
| right | set | Type | unowned |
| weak | willSet |
Swift Whitespace
Swift is not like C/C++ or Java, which completely ignore whitespace. Swift has certain requirements for whitespace usage, but it is not as strict as Python's indentation requirements.
In Swift, operators cannot directly follow a variable or constant. For example, the following code will cause an error:
let a= 1 + 2
The error message is:
error: prefix/postfix '=' is reserved
It roughly means that the usage of the equals sign directly following or preceding is reserved.
The following code will still cause an error (continue to pay attention to whitespace):
let a = 1+ 2
The error message is:
error: consecutive statements on a line must be separated by ';'
This is because Swift considers the statement to have ended at `1+`, and `2` is the next statement.
Only by writing it this way will there be no error:
let a = 1 + 2; // 编码规范推荐使用这种写法 let b = 3+4 // 这样也是OK的
Swift Literals
The so-called literal refers to a value such as a specific number, string, or boolean, which can directly indicate its own type and be assigned to a variable. For example:
42 // 整型字面量 3.14159 // 浮点型字面量 "Hello, world!" // 字符串型字面量 true // 布尔型字面量
Printing Output
Swift uses the print function to print output:
print("Example") // 输出 Example
The print function is a global function, and its complete function signature is:
public func print(items: Any..., separator: String = default, terminator: String = default)
If we want it to output without a newline, just set the last parameter to an empty string:
for x in 0...10{
print("\(x) ", terminator: "")
}
print()
The output result is:
0 1 2 3 4 5 6 7 8 9 10
If you need to receive user input, you can usereadLine():
let theInput = readLine()Other Extensions