Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Swift Basic Syntax

Swift Basic Syntax

Swift's syntax is designed to be "concise and safe"; many rules that C-family languages leave to the programmer's discipline are enforced by the compiler in Swift.

This article covers the most basic syntax elements: importing modules, semicolons, comments, identifiers, keywords, statements and expressions, input and output, and conditional compilation.

These topics may seem trivial, but every article that follows will use them.


import and Foundation

Swift uses import to bring in other modules, similar to Python's import.

The standard library is available automatically and needs no import; print, Array, and String all belong to it.

As soon as you need capabilities like dates, files, networking, or JSON parsing, you must import Foundation.

Example

import Foundation

// Use Date and DateFormatter provided by Foundation

let now

=

Date

(

timeIntervalSince1970

:

0

)

let formatter

=

DateFormatter

(

)

formatter.

dateFormat

=

"yyyy-MM-dd"

formatter.

timeZone

=

TimeZone

(

identifier

:

"UTC"

)

print

(

formatter.

string

(

from

:

now

)

)

Running result:



1970-01-01

There are several other common import forms:

Syntax Meaning
import Foundation Import an entire module and use its public symbols
import func Foundation.sqrt Import only one function to avoid naming conflicts
import struct Foundation.Date Import only one type
@testable import RunoobKit Import and expose internal members, for testing only

Note:Do not confuse import Cocoa Do not write it into example code — it is a macOS-only UI framework and cannot compile on Linux or iOS. Cross-platform code uniformly uses import Foundation。


Semicolon

Swift does not require a semicolon at the end of every statement, similar to Go and unlike C or Java.

Semicolons are required only when multiple statements are written on the same line.

Example

// Semicolons are usually unnecessary

let a

=

1

let b

=

2

print

(

a

b

)

// When writing multiple statements on one line, they must be separated by semicolons

let c

=

3

;

let d

=

4

;

print

(

c

d

)

Running result:



3

7

Although semicolons can be omitted, adding them is not an error, so developers coming from other languages will not run into trouble out of habit.


Notes

Swift supports single-line and multiline comments, and multiline comments can be nested — a feature many languages lack.

A single-line comment begins with two slashes and can be placed after code.

Example

// This is a whole-line comment

let site

=

"www.runoob.com"

 

// This is an end-of-line comment

print

(

site

)

Multiline comments are enclosed by /* and */ and may be nested, so you can safely comment out a large block of code that already contains comments.

Example

/* Outer comment begins
   /* Inner comment: Swift allows nesting */

   Outer comment ends

*/

print

(

"RUNOOB nested comment test passed"

)

Running result:



RUNOOB 嵌套注释测试通过

In C or Java, a nested multiline comment would end early at the first */, causing a compile error; Swift has no such problem.

In addition, /// documentation comments written above a declaration are recognized by Xcode for generating Quick Help and documentation.


Identifiers and naming conventions

An identifier is the name given to a variable, constant, function, or type.

Swift identifiers are case-sensitive and support almost all Unicode characters, including Chinese and Greek letters.

Example

// Chinese identifier

let courseName

=

"Swift Tutorial"

// Greek letter identifier

let π

=

3.14159

print

(

courseName, π

)

Running result:



Swift 教程 3.14159

If you must use a keyword as a name, you can wrap it in backticks, but this is not recommended.

Example

// class is a keyword; wrapped in backticks it can be used as a variable name

let `

class

`

=

"Swift 6"

print

(

`

class

`

)

Running result:



Swift 6

In real projects, community conventions matter more than mere compilability; it is worth building the following naming conventions from the start.

object Convention Example
Variables, constants, functions lowerCamelCase, starting with a lowercase letter siteName、fetchData()
Types (class, struct, enum, protocol) UpperCamelCase, starting with an uppercase letter SiteManager、HTTPClient
Boolean Start with is, has, can, or should isLoading、hasNext
Constant lowerCamelCase, not all uppercase maxRetryCount
Abbreviations Use consistent capitalization; do not mix styles url、URLSession

Note:Swift allows emoji as identifiers, but do not use them in formal projects — they make code hard to search and maintain.


The keyword

Keywords are words reserved by the language and cannot be used directly as identifiers.

Swift has quite a few keywords, but they are easy to remember once grouped by purpose; the table below lists them by category.

Category The keyword
Declaration class、struct、enum、protocol、extension、func、let、var、init、deinit、subscript、typealias、associatedtype、import、operator、precedencegroup、macro、inout
Access Control open、public、package、internal、fileprivate、private
Statement if、else、guard、switch、case、default、for、while、repeat、break、continue、fallthrough、return、throw、defer、do、catch、where、in
Expressions and types as、is、try、await、async、throws、rethrows、some、any、self、Self、super、nil、true、false
Modifiers static、class、final、override、lazy、weak、unowned、mutating、nonmutating、indirect、required、convenience、dynamic

Some of these are "contextual keywords", such as get, set, willSet, didSet, lazy, and weak; they have special meaning only in particular positions and can still be used as ordinary names elsewhere.

There is also a set of special literals beginning with #, used to obtain code location information at compile time.

Special literals Meaning
#file The full path of the current file
#fileID The module name plus filename of the current file, shorter than #file
#line The current line number
#column The current column number
#function The current function name
#dsohandle The current dynamic shared object handle

Example

func runoob

(

)

{

    print

(

"Current function: (#function)"

)

}

runoob

(

)

Running result:



当前函数名:runoob()

Note:These literals were written as _FILE_、_LINE_、_FUNCTION_, all with underscores and in all caps. That spelling in older tutorials no longer compiles.


Statements and Expressions

Distinguishing statements from expressions is key to understanding Swift syntax.

An expression evaluates to a value, while a statement performs an action and has no value of its own.

Example

// Statement: performs an action

var total

=

0

// Expression: has a value and can be assigned to another variable

let sum

=

1

2

total

=

sum

10

print

(

"total ="

, total

)

Running result:



total = 30

1 + 2 is an expression whose value is 3; total = sum * 10 is a statement that performs the assignment.

In Swift, constructs like if, switch, and do can also return a value as expressions in certain situations, such as assigning a branch result to a variable, but that is not the focus of this article.

Also note that Swift expressions are never "accidentally evaluated": if the compiler finds that a standalone expression has no side effects, it issues a warning reminding you that you may have forgotten to use the result.


print and readLine

The standard library provides the simplest pair of I/O functions: print handles output and readLine reads a line of input.

print's modern signature is print(_ items: Any..., separator: String = " ", terminator: String = "\n").

Example

// By default separator is a space and terminator is a newline

print

(

"Runoob"

,

"Swift"

,

"6"

)

// Custom separator and terminator

print

(

"RUNOOB"

,

"Tutorial"

, separator

:

" - "

, terminator

:

"!\n"

)

Running result:



Runoob Swift 6

RUNOOB - 教程!

The underscore _ before the parameter means no argument label is needed when calling, so you write print("Hello") directly, not print(items: "Hello").

readLine reads a line from standard input and returns String? because the input may end.

Example

print

(

"Please enter the site name: "

, terminator

:

""

)

if

let input

=

readLine

(

)

{

    print

(

"You entered: (input)"

)

}

Result (after typing RUNOOB and pressing Enter):



请输入站点名称:你输入的是:RUNOOB

Handling the return value with if let avoids a crash that forced unwrapping could cause.

Note:In older tutorials, println was replaced after Swift 2 by print , and today's print already adds a newline by default.


Conditional Compilation

Swift uses the #if family of directives to selectively include code at compile time; excluded branches are never executed at runtime.

This is very useful for cross-platform code and multi-environment configurations.

Example

#if os(macOS)

print

(

"Currently running on macOS"

)

#elseif os(Linux)

print

(

"Currently running on Linux"

)

#else

print

(

"Other platforms"

)

#endif

#if arch(arm64)

print

(

"arm64 architecture"

)

#elseif arch(x86_64)

print

(

"x86_64 architecture"

)

#endif

Running result:



当前运行在 macOS 上

arm64 架构

The commonly used compilation conditions are listed below.

Conditional Condition checked Example
os() Operating system macOS、iOS、Linux、Windows
arch() CPU architecture arm64、x86_64
swift() Swift language version swift(>=5.9)
compiler() Compiler version compiler(>=6.0)
canImport() Whether a module can be imported canImport(UIKit)
targetEnvironment() Target environment targetEnvironment(simulator)

swift() and compiler() are easy to confuse: the former checks the current language mode, the latter the compiler version.

Example

#if compiler(>=6.0)

print

(

"Compiler version is at least 6.0"

)

#endif

#if swift(>=6.0)

print

(

"Language mode is at least 6.0"

)

#else

print

(

"Current language mode is below 6.0"

)

#endif

Running in default mode on a Swift 6.3 compiler gives:



编译器版本不低于 6.0

当前语言模式低于 6.0

The reason is that new projects in Xcode 16 default to Swift 5 language mode; only when the language mode is switched to Swift 6 does swift(>=6.0) hold.

To check "whether the system version supports a certain API", use another directive, #available, which checks at runtime.

Example

if

#available(macOS 11.0, *) {

    print

(

"The system supports macOS 11.0 and later features"

)

}

else

{

    print

(

"System version too low"

)

}

Running result:



系统支持 macOS 11.0 及以上特性

The trailing asterisk * means "no version restriction on other platforms" and cannot be omitted.

Note:#if is a compile-time branch; excluded code is not compiled;#available is a runtime check; both branches are compiled and only one is chosen at execution time.


Common questions

Here are the questions beginners most often ask at the basic syntax stage.

Why does writing a number in my if condition cause an error?

Swift conditions must be of type Bool; a construct like if 1 is invalid, and there is no rule that "0 is false and nonzero is true".

Can I use Date without writing import?

No. Date belongs to Foundation and requires import Foundation first; only standard library types like String, Int, and Array need no import.

Can you write comments inside comments?

Yes. Swift's multiline comments support nesting, a convenience compared with C-family languages.

Can print output custom types?

Yes. By default it prints the type name and member information; make the type conform to CustomStringConvertible to customize the output.