Swift Basic Syntax
In the previous chapter, we discussed how to create a "Hello, World!" program in Swift. Let's review it now.
If you are creating an OS X playground, you need to import Cocoa:
import Cocoa
/* My first Swift program */
var myString = "Hello, World!"
print(myString)
If we want to create an iOS playground, we need to import UIKit:
import UIKit
var myString = "Hello, World!"
print(myString)
Executing the above program will output:
Hello, World!
The above code represents the basic structure of a Swift program. Next, we will detail the components of this structure.
Swift Import
We can use the import statement to include 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.
Cocoa itself is written in Objective-C, which is a strict superset of C, so we can easily incorporate C code, or even C++ code, into Swift applications.
Swift Tokens
A 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:
print("test!")
The above statement consists of three symbols: the word (print), the symbol ((), and the string ("test").
print
(
"test!"
)
Comments
Swift comments are very similar to C comments. Single-line comments begin with two forward slashes:
// This is a comment
Multi-line comments start with /* and end with */:
/* This is also a comment,
but spans multiple lines */
Unlike C, Swift's multi-line comments can be nested within other multi-line comments. You can insert one multi-line comment block inside another. When the second comment block is closed, it continues the first comment block:
/* 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 */
Nested multi-line comments allow you to comment out blocks of code more quickly and easily, even if the code already contains comments.
Semicolons
Unlike other languages, Swift does not require a semicolon (;) at the end of each statement. However, you must use a semicolon if you are writing multiple statements on the same line:
import Cocoa
/* My first Swift program */
var myString = "Hello, World!"; print(myString)
Identifiers
Identifiers are names given to variables, constants, methods, functions, enumerations, structures, classes, protocols, etc. The letters that make up identifiers have certain rules. The naming rules for identifiers in Swift are as follows:
-
-
-
For example: userName, User_Name, _sys_val, and 身高 are valid identifiers, while 2mail, room#, and class are invalid identifiers.
Note: Swift uses Unicode encoding for letters. Unicode is a unified coding system that includes Asian character encodings such as Chinese, Japanese, and Korean characters, as well as emojis used in chat tools.
If you must use a keyword as an identifier, you can surround it with backticks (`), for example:
let `class` = "tutorialpro"
Keywords
Keywords are reserved character sequences similar to identifiers, which cannot be used as identifiers unless enclosed by backticks (`). Keywords are predefined reserved identifiers with special meanings to the compiler. Common keywords include the following four types.
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
The Swift language does not completely ignore whitespace like C/C++ and Java; it has certain requirements for whitespace usage, but it is not as strict as Python's indentation rules.
In Swift, operators cannot directly follow variables or constants. For example, the following code will result in an error:
let a= 1 + 2
The error message is:
error: prefix/postfix '=' is reserved
This means that using the equals sign directly before or after is reserved.
The following code will also result in 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 end at 1+
, and 2
to be the next statement.
Only this way will not result in an error:
let a = 1 + 2; // Recommended coding style
let b = 3+4 // This is also OK
Swift Literals
Literals are values such as specific numbers, strings, or boolean values that directly indicate their type and assign a value to a variable. For example:
42 // Integer literal
3.14159 // Floating-point literal
"Hello, world!" // String literal
true // Boolean literal
Printing Output
Swift uses the print
function for output:
print("tutorialpro") // Outputs tutorialpro
The print
function is a global function with the complete signature:
public func print(items: Any..., separator: String = default, terminator: String = default)
If you want the output to not include a newline, simply set the last parameter to an empty string:
for x in 0...10 {
print("\(x) ", terminator: "")
}
print()
The output will be:
0 1 2 3 4 5 6 7 8 9 10
To receive user input, you can use readLine()
:
let theInput = readLine()