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

Swift 泛型

系统核对 Swift 泛型函数与类型推断、泛型栈与泛型类、类型约束与 where 子句、协议关联类型 associatedtype 以及普通与条件泛型扩展。

学完这一章,你能够

  • 系统核对 Swift 泛型函数与类型推断、泛型栈与泛型类、类型约束与 where 子句、协议关联类型 associatedtype 以及普通与条件泛型扩展。

泛型函数、类型参数与类型推断

泛型(Generics)将类型本身抽象为参数,使同一套算法或数据结构能够安全复用在 `Int`、`String` 与自定义类型上,并在编译期保持完整类型检查;标准库中的 `Array`、`Dictionary` 与 `Optional` 全是泛型类型。相比为每种类型手写重复的 `swapInt`/`swapString`,泛型彻底消除了机械复制。

泛型函数在函数名后通过尖括号声明占位类型参数(如 `func swapValues<T>(_ a: inout T, _ b: inout T)`,多类型参数写作 `<T, U>`),调用时由编译器依据实参自动推断 `T`(交换字符串与整数各得预期结果)。若函数体内需要使用 `==` 查找元素下标,则必须施加 `T: Equatable` 约束,否则编译器拒绝未声明能力的操作。

泛型类型、类型约束与 where 子句

结构体、类与枚举均可声明为泛型,如 `struct Stack<Element>` 与 `class Box<Value>`。不同实参特化出的 `Stack<Int>` 与 `Stack<String>` 属于完全独立的强类型,无法混用或互赋;创建空栈无法从上下文推断类型时,须显式写明 `Stack<Int>()`。

无约束的类型参数几乎无法执行特定操作,通过协议约束(如 `T: Comparable` 求较大值、`T: Hashable & CustomStringConvertible` 组合约束)或类继承约束(如 `T: BaseEntity`)即可安全调用对应能力。

当约束条件较多或需要表达关联类型相等关系时,使用 `where` 子句可读性更高:既可用于条件扩展(`extension Stack where Element: Equatable` / `Comparable`),也可用于泛型函数要求两集合元素类型完全一致(`where C1.Element: Equatable, C1.Element == C2.Element`,如统计 `[1,2,3,4]` 与 `[2,4,6]` 共有元素个数为 `2`)。

关联类型 associatedtype 与条件泛型扩展

协议不支持尖括号类型参数列表,但可用 `associatedtype Item` 声明占位关联类型,由遵循者通过方法签名自动推断(如 `IntList`)或 `typealias Item = String` 显式指定(如 `StringList`)。带关联类型的协议通常配合泛型参数 `func total<C: Container>(_ c: C)` 使用,以在编译期静态解析具体关联类型。

扩展泛型类型时无需重申类型参数列表,既可编写面向所有 `Element` 的通用扩展,也可添加精确相等条件约束 `extension Stack where Element == String`,使 `joined()` 仅对字符串栈生效。本站离线校验器已核对全部泛型特化、约束与条件扩展行为。

泛型常见问题

四条核心辨析:泛型擅长在编译期定型同一算法多类型复用,协议擅长定义抽象能力边界,二者常结合使用;调用点类型确定且重视性能用泛型,运行时需异构混装才用 `any`;Swift 编译器可通过泛型特化(specialization)消除抽象开销;泛型内不能直接写 `==` 是因未约束 `Equatable`。

Swift 泛型类型约束四种常见写法

写法示例说明
尖括号内约束func f<T: Comparable>(_ x: T)紧凑直接,适合单参数简单协议约束。
where 子句约束func f<T>(_ x: T) where T: Comparable适合多约束或跨类型关联相等条件。
协议组合T: Hashable & CustomStringConvertible使用 & 要求类型同时满足多个协议。
类约束T: BaseEntity要求类型参数必须是指定基类或其子类。

运行离线 Python 校验:Swift 泛型交换、Stack 特化、where 约束与 associatedtype

含完整源码 · 290 行
展开查看收起
python
"""Offline CPython 3.12.14 semantic verifier for Swift Generics (CH33)."""
import json


class GenericConstraintError(TypeError):
    pass


def swap_pair(a, b):
    if type(a) is not type(b):
        raise GenericConstraintError("Generic swap requires both arguments to share type T")
    return b, a


def find_index(value, array: list) -> int | None:
    for idx, item in enumerate(array):
        if item == value:
            return idx
    return None


class Stack:
    def __init__(self, element_type: type) -> None:
        self.element_type = element_type
        self._items: list = []

    def push(self, item) -> None:
        if not isinstance(item, self.element_type):
            raise GenericConstraintError(f"Expected {self.element_type.__name__}, got {type(item).__name__}")
        self._items.append(item)

    def pop(self):
        return self._items.pop() if self._items else None

    @property
    def top(self):
        return self._items[-1] if self._items else None

    @property
    def is_empty(self) -> bool:
        return len(self._items) == 0

    def contains(self, item) -> bool:
        return item in self._items

    def max_element(self):
        return max(self._items) if self._items else None

    def joined_strings(self, sep: str = " - ") -> str:
        if self.element_type is not str:
            raise GenericConstraintError("where Element == String constraint not satisfied")
        return sep.join(self._items)


class Box:
    def __init__(self, value) -> None:
        self.value = value
        self.value_type = type(value).__name__


class BaseEntity:
    pass


class SubEntity(BaseEntity):
    pass


def generic_max(a, b):
    return a if a > b else b


def hashable_desc(value) -> str:
    hash(value)  # verifies Hashable
    return f"值:{value},描述:{value}"


def check_subclass(item) -> str:
    if not isinstance(item, BaseEntity):
        raise GenericConstraintError("T must inherit from BaseEntity")
    return f"类型是 {type(item).__name__}"


def common_pairs(a: list, b: list) -> int:
    if a and b and type(a[0]) is not type(b[0]):
        raise GenericConstraintError("where C1.Element == C2.Element violated")
    return sum(1 for x in a if x in b)


class IntList:
    item_type = "Int"

    def __init__(self) -> None:
        self._items: list[int] = []

    def append(self, item: int) -> None:
        self._items.append(item)

    @property
    def count(self) -> int:
        return len(self._items)

    def __getitem__(self, i: int) -> int:
        return self._items[i]


class StringList:
    item_type = "String"

    def __init__(self) -> None:
        self._items: list[str] = []

    def append(self, item: str) -> None:
        self._items.append(item)

    @property
    def count(self) -> int:
        return len(self._items)

    def __getitem__(self, i: int) -> str:
        return self._items[i]


def case_generic_swap_and_index():
    s1, s2 = swap_pair("example.com", "SWIFT")
    x, y = swap_pair(10, 99)
    idx = find_index("swift", ["rust", "swift", "kotlin"])
    mismatch_blocked = False
    try:
        swap_pair(10, "ten")
    except GenericConstraintError:
        mismatch_blocked = True

    actual = {
        "swapped_str": f"{s1} / {s2}",
        "swapped_int": [x, y],
        "found_index": idx,
        "type_mismatch_blocked": mismatch_blocked,
    }
    expected = {
        "swapped_str": "SWIFT / example.com",
        "swapped_int": [99, 10],
        "found_index": 1,
        "type_mismatch_blocked": True,
    }
    return {
        "name": "generic_swap_and_equatable_index",
        "summary": "Verify generic swap<T> type inference & homogeneity check plus Equatable index search.",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_generic_stack_and_box():
    int_stack = Stack(int)
    for n in (1, 2, 3):
        int_stack.push(n)
    str_stack = Stack(str)
    str_stack.push("alpha")
    str_stack.push("beta")
    top1 = str_stack.top
    popped = str_stack.pop()
    top2 = str_stack.top
    box = Box("Swift 泛型")

    cross_push_blocked = False
    try:
        int_stack.push("not-an-int")
    except GenericConstraintError:
        cross_push_blocked = True

    actual = {
        "int_top": int_stack.top,
        "str_trace": [top1, popped, top2],
        "box_value": box.value,
        "box_type": box.value_type,
        "cross_type_blocked": cross_push_blocked,
    }
    expected = {
        "int_top": 3,
        "str_trace": ["beta", "beta", "alpha"],
        "box_value": "Swift 泛型",
        "box_type": "str",
        "cross_type_blocked": True,
    }
    return {
        "name": "generic_stack_and_box_types",
        "summary": "Verify generic Stack<Int> and Stack<String> enforce element type specialization and Box<Value> type inference.",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_constraints_and_where():
    st = Stack(int)
    for n in (30, 10, 20):
        st.push(n)
    pairs = common_pairs([1, 2, 3, 4], [2, 4, 6])
    diff_elem_blocked = False
    try:
        common_pairs([1, 2], ["1", "2"])
    except GenericConstraintError:
        diff_elem_blocked = True

    actual = {
        "max_int": generic_max(3, 9),
        "max_str": generic_max("apple", "swift"),
        "hashable_info": hashable_desc("SWIFT"),
        "class_constraint": check_subclass(SubEntity()),
        "where_contains_10": st.contains(10),
        "where_max": st.max_element(),
        "where_common_pairs": pairs,
        "where_same_element_enforced": diff_elem_blocked,
    }
    expected = {
        "max_int": 9,
        "max_str": "swift",
        "hashable_info": "值:SWIFT,描述:SWIFT",
        "class_constraint": "类型是 SubEntity",
        "where_contains_10": True,
        "where_max": 30,
        "where_common_pairs": 2,
        "where_same_element_enforced": True,
    }
    return {
        "name": "type_constraints_and_where_clause",
        "summary": "Verify Comparable/Hashable/class constraints and where-clause C1.Element == C2.Element matching.",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_associatedtype_and_extension():
    ints = IntList()
    for v in (100, 200, 300):
        ints.append(v)
    strs = StringList()
    strs.append("Swift")
    strs.append("Generics")

    str_stack = Stack(str)
    for s in ("Swift", "TypeSafe", "example.com"):
        str_stack.push(s)

    int_stack_join_blocked = False
    try:
        Stack(int).joined_strings()
    except GenericConstraintError:
        int_stack_join_blocked = True

    actual = {
        "int_list": [ints.count, ints[0], ints.item_type],
        "string_list": [strs.count, strs[1], strs.item_type],
        "joined_string_stack": str_stack.joined_strings(),
        "where_element_eq_string_enforced": int_stack_join_blocked,
    }
    expected = {
        "int_list": [3, 100, "Int"],
        "string_list": [2, "Generics", "String"],
        "joined_string_stack": "Swift - TypeSafe - example.com",
        "where_element_eq_string_enforced": True,
    }
    return {
        "name": "associatedtype_and_generic_extension",
        "summary": "Verify Container associatedtype Item inference/typealias and exact-type conditional extension where Element == String.",
        "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_generic_swap_and_index(),
            case_generic_stack_and_box(),
            case_constraints_and_where(),
            case_associatedtype_and_extension(),
        ],
    }
    print(json.dumps(report, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
核对 swap<T> 同质类型检查、Stack<Int>/Stack<String> 隔离、Comparable/Hashable/C1.Element==C2.Element 约束及 where Element==String 拼接。

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

本地运行

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

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

本章附件与实例包

下载课程关联工程包:Swift

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

下载课程关联工程包:Swift

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

无约束的 T 可能是未实现相等比较的任意类型,因此必须加上 T: Equatable 约束;Element: Equatable 是协议遵循约束(任意实现 Equatable 的类型均可),而 Element == String 是精确类型相等约束(仅当元素恰好是 String 时生效)。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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