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

Swift 可选链

系统核对 Swift 可选链(?.)访问属性、调用 Void/有返回值方法、下标 ?[i] 访问、多层链接短路、与空合运算符 ?? 协作及可选链赋值的右侧短路求值语义。

学完这一章,你能够

  • 系统核对 Swift 可选链(?.)访问属性、调用 Void/有返回值方法、下标 ?[i] 访问、多层链接短路、与空合运算符 ?? 协作及可选链赋值的右侧短路求值语义。

可选链语法与结果可选包装规则

可选链(Optional Chaining)通过在可能为 `nil` 的可选值后追加 `?` 来安全访问其属性、方法或下标:只要链上任意一环为 `nil`,整个表达式立刻短路返回 `nil` 而不会崩溃。以 `Person -> Residence? -> Address? -> Room` 链式模型为例,无论末端成员原本是否为可选类型,经由可选链读取的结果总会再包裹一层可选(例如原本为非可选 `Int` 的 `numberOfRooms` 经 `person.residence?.numberOfRooms` 访问后变为 `Int?`),因此读取真实值时须配合 `if let`、`guard let` 或 `??` 解包。

通过可选链访问属性、调用方法与访问下标

当 `Person` 实例的 `residence` 仍为 `nil` 时,`person.residence?.numberOfRooms` 直接求值为 `nil`;待挂载包含两个房间的 `Residence` 实例后,同一表达式安全解包出 `2`。需注意即便 `person` 用 `let` 声明,修改 `person.residence = residence` 依然合法,因为 `let` 对类实例仅锁定引用指向不变,并不冻结其可变属性。

对方法使用可选链时,返回 `Void` 的方法(如 `printNumberOfRooms()`)结果会被包装成 `Void?`,于是可直接用 `!= nil` 判断方法是否实际被执行;同理,返回 `String` 的方法经可选链调用后会得到 `String?`。

对可选对象使用下标时问号写在方括号之前:`person.residence?[0].name` 中的 `?` 作用于可选的 `residence`,而非数组元素;一旦 `residence` 存在,其内部非可选数组 `rooms` 则直接写作 `rooms[1]`。务必警惕:可选链只防 `nil`,不防数组越界,访问 `residence?.rooms[99]` 仍会在运行时崩溃。本站离线校验器已核对属性、方法与下标可选链及越界陷阱。

多层可选链、空合运算符与赋值右侧短路

多个可选环节可以连续串联,如 `person.residence?.address?.buildingIdentifier()` 依次跨越 `Residence?`、`Address?` 与方法返回 `String?`,且多层可选链不会叠成多重嵌套可选(仍保持单层 `String?`);链中任意一环断开便立即短路返回 `nil`。

将可选链与空合运算符 `??` 组合(如 `person.residence?.numberOfRooms ?? 0` 或 `address?.buildingName ?? "未填写"`)可一步恢复为非可选默认值;但若业务需要区分“缺失(`nil`)”与“确实为 `0`”,仍应使用 `if let` 显式分支。

可选链也可以位于赋值等号左侧(如 `someone.residence?.address = makeAddress(...)`)。一旦左侧链条在 `residence` 处为 `nil`,赋值不仅不会执行,等号右侧的 `makeAddress(...)` 表达式也会被彻底跳过而不发生任何副作用(计数器保持 `0`);只有前置链条有效时右侧才会被求值(计数器递增为 `1`)。

可选链常见疑问辨析

日常使用可选链需厘清五点:第一,结果一律转为可选是因为必须能够表达“链条中途断开”的状态;第二,相比强制解包 `!` 遇 `nil` 直接崩溃,可选链更安全,`!` 仅限逻辑 100% 非空场合;第三,判断无返回值方法是否执行可直接检查 `!= nil`;第四,可选链可无缝跨越不同类型的可选属性与方法;第五,可选链无法替代数组越界或类型转换失败判断,需要精细分支处理时仍应使用 `if let`/`guard let`/`switch`。

可选链表达式返回类型包装规律

表达式成员原始类型可选链结果类型
person.residenceResidence?Residence?
person.residence?.numberOfRoomsIntInt?
person.residence?.printNumberOfRooms()VoidVoid?
person.residence?[0].nameStringString?

运行离线 Python 校验:Swift 可选链属性/方法/下标访问、多层短路与赋值右侧跳过

含完整源码 · 223 行
展开查看收起
python
"""Offline CPython 3.12.14 semantic verifier for Swift Optional Chaining (CH28)."""
import json


class Room:
    def __init__(self, name: str) -> None:
        self.name = name


class Address:
    def __init__(self, building_number: str, street: str, building_name: str | None = None) -> None:
        self.building_name = building_name
        self.building_number = building_number
        self.street = street

    def building_identifier(self) -> str | None:
        if self.building_name is not None:
            return f"{self.building_name} {self.building_number}"
        return self.building_number


class Residence:
    def __init__(self) -> None:
        self.rooms: list[Room] = []
        self.address: Address | None = None
        self.printed: list[str] = []

    @property
    def number_of_rooms(self) -> int:
        return len(self.rooms)

    def __getitem__(self, idx: int) -> Room:
        return self.rooms[idx]

    def print_number_of_rooms(self) -> tuple[()]:
        self.printed.append(f"房间数量:{self.number_of_rooms}")
        return ()  # Swift Void


class Person:
    def __init__(self) -> None:
        self.residence: Residence | None = None


def opt_chain(val, *steps):
    cur = val
    for fn in steps:
        if cur is None:
            return None
        cur = fn(cur)
    return cur


def case_property_and_method_chaining():
    alice = Person()
    before = opt_chain(alice.residence, lambda r: r.number_of_rooms)

    res = Residence()
    res.rooms.append(Room("客厅"))
    res.rooms.append(Room("书房"))
    alice.residence = res

    after = opt_chain(alice.residence, lambda r: r.number_of_rooms)
    void_ok = opt_chain(alice.residence, lambda r: r.print_number_of_rooms())
    nobody = Person()
    void_fail = opt_chain(nobody.residence, lambda r: r.print_number_of_rooms())

    actual = {
        "rooms_before_nil": before is None,
        "rooms_after": after,
        "method_ok_not_nil": void_ok is not None,
        "method_printed": res.printed,
        "method_fail_is_nil": void_fail is None,
    }
    expected = {
        "rooms_before_nil": True,
        "rooms_after": 2,
        "method_ok_not_nil": True,
        "method_printed": ["房间数量:2"],
        "method_fail_is_nil": True,
    }
    return {
        "name": "property_and_method_chaining",
        "summary": "Verify optional chaining wraps property Int as Int? and Void method calls as Void? while returning nil when chain breaks.",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_subscript_and_multilevel():
    alice = Person()
    res = Residence()
    res.rooms = [Room("客厅"), Room("书房")]
    alice.residence = res

    first_name = opt_chain(alice.residence, lambda r: r[0].name)
    second_name = opt_chain(alice.residence, lambda r: r.rooms[1].name)

    oob_trapped = False
    try:
        opt_chain(alice.residence, lambda r: r.rooms[99].name)
    except IndexError:
        oob_trapped = True

    addr = Address("100", "example.com", "蓝天大厦")
    alice.residence.address = addr
    id_with_name = opt_chain(alice.residence, lambda r: r.address, lambda a: a.building_identifier())

    alice.residence.address = Address("200", "example.com")
    id_no_name = opt_chain(alice.residence, lambda r: r.address, lambda a: a.building_identifier())

    empty_person = Person()
    empty_street = opt_chain(empty_person.residence, lambda r: r.address, lambda a: a.street)

    actual = {
        "first_room": first_name,
        "second_room": second_name,
        "oob_still_traps": oob_trapped,
        "id_with_building_name": id_with_name,
        "id_without_building_name": id_no_name,
        "empty_person_street_nil": empty_street is None,
    }
    expected = {
        "first_room": "客厅",
        "second_room": "书房",
        "oob_still_traps": True,
        "id_with_building_name": "蓝天大厦 100",
        "id_without_building_name": "200",
        "empty_person_street_nil": True,
    }
    return {
        "name": "subscript_and_multilevel_chaining",
        "summary": "Verify optional chaining on subscripts (with OOB still trapping) and multi-level Person?.residence?.address?.buildingIdentifier().",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_nil_coalescing():
    alice = Person()
    res = Residence()
    res.rooms = [Room("客厅"), Room("书房")]
    res.address = Address("200", "example.com")
    alice.residence = res
    empty = Person()

    actual = {
        "alice_rooms": opt_chain(alice.residence, lambda r: r.number_of_rooms) or 0,
        "empty_rooms": (v if (v := opt_chain(empty.residence, lambda r: r.number_of_rooms)) is not None else 0),
        "street": opt_chain(alice.residence, lambda r: r.address, lambda a: a.street) or "未填写",
        "building_name": opt_chain(alice.residence, lambda r: r.address, lambda a: a.building_name) or "未填写",
    }
    expected = {
        "alice_rooms": 2,
        "empty_rooms": 0,
        "street": "example.com",
        "building_name": "未填写",
    }
    return {
        "name": "nil_coalescing_combination",
        "summary": "Verify optional chaining combined with nil-coalescing operator ?? to recover non-optional fallback values.",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_chaining_assignment_short_circuit():
    created_count = 0

    def make_address(street: str) -> Address:
        nonlocal created_count
        created_count += 1
        return Address("1", street)

    someone = Person()
    if someone.residence is not None:
        someone.residence.address = make_address("不会被执行")
    count_after_nil_chain = created_count

    other = Person()
    other.residence = Residence()
    if other.residence is not None:
        other.residence.address = make_address("example.com")
    count_after_valid_chain = created_count

    actual = {
        "count_when_chain_nil": count_after_nil_chain,
        "count_when_chain_valid": count_after_valid_chain,
        "other_street": opt_chain(other.residence, lambda r: r.address, lambda a: a.street),
    }
    expected = {
        "count_when_chain_nil": 0,
        "count_when_chain_valid": 1,
        "other_street": "example.com",
    }
    return {
        "name": "chaining_assignment_short_circuit",
        "summary": "Verify optional chaining assignment skips evaluating RHS expression entirely when the LHS chain breaks at nil.",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main() -> None:
    report = {
        "version": "CPython 3.12.14 offline Swift 5/6 semantic verifier (swiftc absent)",
        "cases": [
            case_property_and_method_chaining(),
            case_subscript_and_multilevel(),
            case_nil_coalescing(),
            case_chaining_assignment_short_circuit(),
        ],
    }
    print(json.dumps(report, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
核对 numberOfRooms 由 nil 到 2、Void? 方法执行判空、rooms[99] 越界仍触发异常、三层地址链、?? 兜底以及链断开时 makeAddress 计数为 0。

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

本地运行

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

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

本章附件与实例包

下载课程关联工程包:Swift

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

下载课程关联工程包:Swift

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

不会被调用。Swift 的可选链赋值具备短路特性:左侧链条一旦遇到 nil,赋值立即中止且不会求值等号右侧的表达式,从而避免无意义的构造与副作用。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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