蓝色天空.知识 · 实践 · 创造
我的收藏
Swift 教程目录 47章
Swift / LEARN BY DOING

Swift 基本语法

系统讲解 import 模块导入、分号规则、可嵌套多行注释、Unicode 与反引号标识符、关键字与编译期位置字面量、语句与表达式、print/readLine 以及 #if 与 #available。

学完这一章,你能够

  • 系统讲解 import 模块导入、分号规则、可嵌套多行注释、Unicode 与反引号标识符、关键字与编译期位置字面量、语句与表达式、print/readLine 以及 #if 与 #available。

模块导入(import / Foundation)与分号规则

Swift 的语法强调“简洁且由编译器保障安全”。标准库中的 `print`、`Array`、`String` 等类型开箱即用,无需显式导入;涉及日期格式化(`Date`、`DateFormatter`)、文件、网络或 JSON 解析时需使用 `import Foundation`。导入支持整模块、按符号精准导入(`import func`/`import struct`)以及单元测试专用的 `@testable import`;跨平台示例应统一导入 `Foundation`,避免使用仅限 macOS 的 `import Cocoa`。

Swift 不强制在语句末尾写分号,单行一条语句直接换行即可;只有在把多条语句写在同一行(例如 `let c = 3; let d = 4; print(c + d)`)时,才必须用分号分隔。保留行尾分号虽不会报错,但社区惯例推荐省略。

嵌套注释、标识符规则与命名约定

Swift 支持 `//` 单行/行尾注释、`/* ... */` 多行注释以及 `///` 文档注释(可由 Xcode 自动解析生成快速帮助)。与 C/Java 不同,Swift 的多行注释允许任意深度嵌套,方便临时注释掉已经包含块注释的大段代码而不会在首个 `*/` 处提前截断。本站离线脚本以词法状态机验证了嵌套注释的准确剥离。

标识符严格区分大小写,且支持绝大多数 Unicode 字符(如中文变量或希腊字母 `π`);若确需复用保留关键字作名称,可用反引号包裹(如 ``let `class` = "Swift 6"``)。实际工程中应遵循统一社区命名规范(变量/常量/函数小驼峰、类型大驼峰、布尔值带 `is`/`has`/`can`/`should` 前缀、缩写词大小写一致),避免使用 emoji 作正式代码标识符。

关键字分类、编译期位置字面量与语句/表达式

Swift 保留关键字可分为声明、访问控制、语句、表达式与类型、修饰符五大类;另有 `get`、`set`、`willSet`、`didSet`、`lazy`、`weak` 等上下文关键字仅在特定语法位置具备特殊含义。以 `#` 开头的编译期特殊字面量(`#file`、`#fileID`、`#line`、`#column`、`#function`、`#dsohandle`)可在编译时展开源码位置信息,已取代 Swift 3 之前全大写带下划线的 `_FILE_`、`_LINE_`、`_FUNCTION_` 旧写法。

表达式用于求值(如 `1 + 2` 产出 `3`),语句用于执行动作(如赋值 `total = sum * 10` 本身不产生值)。现代 Swift 在特定上下文也支持 `if`/`switch` 表达式返回值;同时编译器会针对无副作用的孤立表达式发出警告,防止遗漏结果接收。

基础输入输出(print / readLine)与条件编译

标准库输出函数签名为 `print(_ items: Any..., separator: String = " ", terminator: String = "\n")`:首参数因带下划线 `_` 而省略外部标签,默认空格分隔、换行结尾,且已全面替代 Swift 2 时代的 `println`。标准输入函数 `readLine()` 返回可选类型 `String?`,需配合 `if let` 安全解包以防输入流结束返回 `nil`。

`#if` / `#elseif` / `#else` / `#endif` 在编译期根据 `os()`、`arch()`、`swift()`、`compiler()`、`canImport()` 或 `targetEnvironment()` 选择参与编译的分支。注意 `compiler(>=6.0)` 检查编译器版本,而 `swift(>=6.0)` 检查当前语言模式(Xcode 16 默认新建工程可能处于 Swift 5 语言模式)。与之相对,`#available(macOS 11.0, *)` 属于运行期系统版本检测,两个分支均参与编译,且末尾通配符 `*` 不可省略。

基础语法高频答疑:Swift 要求 `if` 条件严格为 `Bool`,禁止 `if 1` 这类隐式真值判断;`Date` 位于 `Foundation` 模块而非标准库,使用前必须 `import Foundation`;多行注释支持嵌套;`print` 默认即可打印自定义类型,遵循 `CustomStringConvertible` 协议则可定制输出格式。

Swift 模块导入常用写法

写法含义
import Foundation导入整个 Foundation 模块并使用其公开符号。
import func Foundation.sqrt仅导入单个函数,减少命名冲突范围。
import struct Foundation.Date仅导入模块中的单个具体类型。
@testable import SkyKit仅用于单元测试目标,开放被测模块的 internal 成员访问。

Swift 社区标识符命名规范

对象规范示例
变量、常量、函数小驼峰(lowerCamelCase),首字母小写siteName、fetchData()
类型(类、结构体、枚举、协议)大驼峰(UpperCamelCase),首字母大写SiteManager、HTTPClient
布尔值以 is、has、can、should 等谓词开头isLoading、hasNext
常量小驼峰命名,不采用全大写下划线风格maxRetryCount
缩写词保持大小写统一,不在同一词内混写url、URLSession

Swift 保留关键字分类速查

类别关键字
声明class、struct、enum、protocol、extension、func、let、var、init、deinit、subscript、typealias、associatedtype、import、operator、precedencegroup、macro、inout
访问控制open、public、package、internal、fileprivate、private
语句if、else、guard、switch、case、default、for、while、repeat、break、continue、fallthrough、return、throw、defer、do、catch、where、in
表达式与类型as、is、try、await、async、throws、rethrows、some、any、self、Self、super、nil、true、false
修饰符static、class、final、override、lazy、weak、unowned、mutating、nonmutating、indirect、required、convenience、dynamic

编译期源码位置特殊字面量

特殊字面量含义
#file当前源文件完整路径字符串。
#fileID当前模块名与文件名组合,较 #file 更简洁且利于隐私脱敏。
#line当前源码所在行号整数。
#column当前源码所在列号整数。
#function当前所在函数、方法或初始化器名称。
#dsohandle当前动态共享对象句柄指针。

条件编译常用判断指令

条件判断内容示例
os()目标操作系统macOS、iOS、Linux、Windows
arch()目标 CPU 架构arm64、x86_64
swift()当前启用的 Swift 语言模式版本swift(>=5.9)
compiler()Swift 编译器版本compiler(>=6.0)
canImport()检查指定模块在当前平台是否可导入canImport(UIKit)
targetEnvironment()目标运行环境(如模拟器)targetEnvironment(simulator)

离线校验嵌套注释剥离、标识符规范、print/readLine 与 #if/#available 分支

含完整源码 · 172 行
展开查看收起
python
"""Offline Swift 5/6 semantic verification lab for Chapter 04 (basic-syntax)."""
import datetime
import json
import re

VERSION = "CPython 3.12.14 offline Swift 5/6 semantic verifier (swiftc absent)"


def strip_nested_swift_comments(src: str) -> str:
    out = []
    i = 0
    depth = 0
    n = len(src)
    while i < n:
        if depth == 0 and src[i:i + 2] == "//":
            nl = src.find("\n", i)
            i = n if nl == -1 else nl
            continue
        if src[i:i + 2] == "/*":
            depth += 1
            i += 2
            continue
        if depth > 0 and src[i:i + 2] == "*/":
            depth -= 1
            i += 2
            continue
        if depth == 0:
            out.append(src[i])
        i += 1
    if depth != 0:
        raise ValueError("unterminated nested block comment")
    return "".join(out)


def case_foundation_date_and_semicolons():
    epoch = datetime.datetime.fromtimestamp(0, tz=datetime.timezone.utc).strftime("%Y-%m-%d")
    # Single-line statements without semicolons vs same-line statements separated by ';'
    a, b = 1, 2
    c, d = 3, 4
    expected = {
        "utc_epoch": "1970-01-01",
        "sum_ab": 3,
        "sum_cd": 7,
        "import_forms": 4,
    }
    actual = {
        "utc_epoch": epoch,
        "sum_ab": a + b,
        "sum_cd": c + d,
        "import_forms": len(["import Foundation", "import func Foundation.sqrt", "import struct Foundation.Date", "@testable import SkyKit"]),
    }
    return {
        "name": "foundation_date_and_semicolons",
        "summary": "验证 Foundation UTC 纪元日期格式化、四类 import 语法以及单行分号分隔规则",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_nested_comments_and_identifiers():
    snippet = '/* 外层开始 /* 内层嵌套 */ 外层结束 */\nlet 课程名称 = "Swift 教程" // 行尾注释\nlet π = 3.14159\nlet `class` = "Swift 6"\n'
    cleaned = strip_nested_swift_comments(snippet).strip()
    decls = re.findall(r"let\s+(`?\w+`?)\s*=\s*(.+)", cleaned)
    expected = {
        "nested_comment_stripped": True,
        "identifiers": ["课程名称", "π", "`class`"],
        "case_sensitive": True,
    }
    actual = {
        "nested_comment_stripped": "/*" not in cleaned and "*/" not in cleaned and "//" not in cleaned,
        "identifiers": [name for name, _ in decls],
        "case_sensitive": ("siteName" != "SiteName"),
    }
    return {
        "name": "nested_comments_and_identifiers",
        "summary": "通过嵌套多行注释词法剥离器验证 /* /* */ */ 合法性以及 Unicode 与反引号转义标识符",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_keywords_special_literals_and_io():
    # print(_ items: Any..., separator: String = " ", terminator: String = "\n")
    def swift_print(*items, separator=" ", terminator="\n"):
        return separator.join(str(x) for x in items) + terminator

    def simulate_readline(line):
        if line is None:
            return "EOF"
        return f"你输入的是:{line}"

    special_literals = ["#file", "#fileID", "#line", "#column", "#function", "#dsohandle"]
    expected = {
        "default_print": "BlueSky Swift 6\n",
        "custom_print": "BlueSky - 教程!\n",
        "readline_some": "你输入的是:BlueSky",
        "readline_eof": "EOF",
        "expr_statement_total": 30,
        "special_literal_count": 6,
    }
    total = (1 + 2) * 10
    actual = {
        "default_print": swift_print("BlueSky", "Swift", "6"),
        "custom_print": swift_print("BlueSky", "教程", separator=" - ", terminator="!\n"),
        "readline_some": simulate_readline("BlueSky"),
        "readline_eof": simulate_readline(None),
        "expr_statement_total": total,
        "special_literal_count": len(special_literals),
    }
    return {
        "name": "keywords_special_literals_and_io",
        "summary": "校验 print 默认/自定义分隔与终止符、readLine() 可选返回、语句与表达式区别及 # 特殊字面量",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_conditional_compilation_and_availability():
    def eval_compile_flags(os_name, arch_name, compiler_ver, lang_mode):
        out = []
        out.append("macOS" if os_name == "macOS" else ("Linux" if os_name == "Linux" else "Other"))
        if arch_name in ("arm64", "x86_64"):
            out.append(arch_name)
        if compiler_ver >= (6, 0):
            out.append("compiler>=6.0")
        out.append("swift>=6.0" if lang_mode >= (6, 0) else "swift<6.0")
        return out

    def runtime_available(os_name, version, min_macos=(11, 0)):
        if os_name == "macOS":
            return version >= min_macos
        return True  # '*' wildcard covers other platforms

    expected = {
        "xcode16_default_mode": ["macOS", "arm64", "compiler>=6.0", "swift<6.0"],
        "swift6_mode": ["macOS", "arm64", "compiler>=6.0", "swift>=6.0"],
        "macos_14_available": True,
        "macos_10_15_available": False,
        "linux_wildcard_available": True,
    }
    actual = {
        "xcode16_default_mode": eval_compile_flags("macOS", "arm64", (6, 3), (5, 0)),
        "swift6_mode": eval_compile_flags("macOS", "arm64", (6, 3), (6, 0)),
        "macos_14_available": runtime_available("macOS", (14, 0)),
        "macos_10_15_available": runtime_available("macOS", (10, 15)),
        "linux_wildcard_available": runtime_available("Linux", (6, 0)),
    }
    return {
        "name": "conditional_compilation_and_availability",
        "summary": "对比编译期 #if (os/arch/compiler/swift) 与运行期 #available(macOS 11.0, *) 语义差异",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_foundation_date_and_semicolons(),
        case_nested_comments_and_identifiers(),
        case_keywords_special_literals_and_io(),
        case_conditional_compilation_and_availability(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
离线脚本通过嵌套块注释词法剥离、UTC 纪元格式化、print 分隔/终止符、readLine 可选返回以及 compiler() vs swift() 和 #available 分支校验。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a2088.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Swift

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2088.zip

下载课程关联工程包:Swift

课程关联工程包(登记关联47章) · 含当前章节或实例 · mbskycom202612a2087.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

`compiler()` 与 `swift()` 均为编译期条件(被排除分支不参与编译),前者检测编译器版本而后者检测工程当前启用的语言模式;`#available` 则是运行期系统版本检测,两个分支代码都会编译,运行时按宿主机系统版本选择执行路径。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习