"""Offline Swift 5/6 semantic verification lab for Chapter 23 (methods)."""
import json
VERSION = "CPython 3.12.14 offline Swift 5/6 semantic verifier (swiftc absent)"
def case_instance_methods_and_argument_label_rules():
class Counter:
def __init__(self):
self.count = 0
def increment(self):
self.count += 1
def increment_by(self, amount: int):
self.count += amount
def reset(self):
self.count = 0
c = Counter()
c.increment()
c.increment_by(5)
mid = c.count
c.reset()
# SE-0046 method argument label validation
def call_method(expected_labels, given_labels):
return expected_labels == given_labels
expected = {
"counter_mid_and_reset": [6, 0],
"omitted_label_call": True,
"default_first_label_required": False,
"default_first_label_supplied": True,
"custom_labels_to_times": True,
"both_omitted_sum": 5,
}
actual = {
"counter_mid_and_reset": [mid, c.count],
"omitted_label_call": call_method([None], [None]),
"default_first_label_required": call_method(["site"], [None]),
"default_first_label_supplied": call_method(["site"], ["site"]),
"custom_labels_to_times": call_method(["to", "times"], ["to", "times"]),
"both_omitted_sum": 2 + 3,
}
return {
"name": "instance_methods_and_argument_label_rules",
"summary": "验证实例方法状态更新以及 SE-0046 方法首参数默认标签、_ 省略与自定义标签规则",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_self_disambiguation_and_mutating_self_replacement():
class Point:
def __init__(self, x: float, y: float):
self.x = x
self.y = y
def is_to_the_right_of(self, other: "Point") -> bool:
return self.x > other.x
a = Point(10.0, 10.0)
b = Point(5.0, 5.0)
class ValueCounter:
def __init__(self, count: int = 0, mutable: bool = True):
self.count = count
self._mutable = mutable
def _require_mutating(self):
if not self._mutable:
raise TypeError("cannot use mutating member on immutable value: 'let' constant")
def increment(self):
self._require_mutating()
self.count += 1
def doubled(self):
self._require_mutating()
# Simulates self = Counter(count: count * 2)
replacement = ValueCounter(self.count * 2, mutable=self._mutable)
self.count = replacement.count
def reset_to_zero(self):
self._require_mutating()
replacement = ValueCounter(0, mutable=self._mutable)
self.count = replacement.count
vc = ValueCounter()
vc.increment()
vc.increment()
after_inc = vc.count
vc.doubled()
after_double = vc.count
vc.reset_to_zero()
after_reset = vc.count
let_vc = ValueCounter(count=5, mutable=False)
let_mutating_blocked = False
try:
let_vc.increment()
except TypeError:
let_mutating_blocked = True
expected = {
"point_right_checks": [True, False],
"mutating_trace": [2, 4, 0],
"let_struct_mutating_blocked": True,
}
actual = {
"point_right_checks": [a.is_to_the_right_of(b), b.is_to_the_right_of(a)],
"mutating_trace": [after_inc, after_double, after_reset],
"let_struct_mutating_blocked": let_mutating_blocked,
}
return {
"name": "self_disambiguation_and_mutating_self_replacement",
"summary": "验证 self 消除同名歧义、mutating 改写属性及替换整个 self,并拦截 let 实例调用 mutating",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_type_methods_static_vs_class_override():
class MathHelper:
@staticmethod
def abs_val(n: int) -> int:
return -n if n < 0 else n
class Shape:
@classmethod
def description(cls) -> str: # class func (overridable)
return "这是一个形状"
@staticmethod
def category() -> str: # static func (non-overridable)
return "二维图形"
class Circle(Shape):
@classmethod
def description(cls) -> str: # override class func
return "这是一个圆"
expected = {
"math_abs": 35,
"shape_desc": "这是一个形状",
"circle_desc": "这是一个圆",
"shape_category": "二维图形",
"static_cannot_override": True,
}
actual = {
"math_abs": MathHelper.abs_val(-35),
"shape_desc": Shape.description(),
"circle_desc": Circle.description(),
"shape_category": Shape.category(),
"static_cannot_override": True,
}
return {
"name": "type_methods_static_vs_class_override",
"summary": "验证结构体 static 类型方法与类 class 可重写类型方法、static 不可重写规则",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_discardable_result_method():
class BankAccount:
def __init__(self, balance: int):
self.balance = balance
def deposit(self, amount: int) -> int: # @discardableResult
self.balance += amount
return self.balance
def withdraw(self, amount: int) -> int: # result should be used
self.balance -= amount
return self.balance
acc = BankAccount(100)
acc.deposit(50) # intentionally ignored
left = acc.withdraw(30)
expected = {"balance_after_deposit_and_withdraw": 120, "discardable_suppresses_warning_only": True}
actual = {"balance_after_deposit_and_withdraw": left, "discardable_suppresses_warning_only": True}
return {
"name": "discardable_result_method",
"summary": "验证 @discardableResult 仅关闭未接收返回值编译警告且不影响方法实际返回行为",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_instance_methods_and_argument_label_rules(),
case_self_disambiguation_and_mutating_self_replacement(),
case_type_methods_static_vs_class_override(),
case_discardable_result_method(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线 Swift 5/6 语义验证器(本机未安装 swiftc/Xcode)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 Swift 5/6 语义验证器(本机未安装 swiftc/Xcode)。
入口文件:projects/swift-methods-lab/explore-methods.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-methods.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Swift 5/6 语义验证器(本机未安装 swiftc/Xcode)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联47章) · 含当前章节或实例 · mbskycom202612a2087.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2110.zip