Menu
CoddyTech

组合对象

Coddy 面向 Swift 开发者的 GDScript 课程的第 29 课,共 48 课。

Swift 中的类类型属性会共享其引用的对象,即使使用 let 声明也是如此;值类型属性的复制行为则不同。GDScript 对象字段同样会保留协作者,而不会克隆它们。外部修改可能仍然可见,因此要谨慎注入依赖。Swift ARC 和 Godot RefCounted 可能会保留强引用循环;必要时,请明确所有权关系或使用弱引用。

完整的 Swift 程序;将列出的所有 .swift 文件一起编译:

Swift 文件 Note.swift:

final class Note { var text="a" }

Swift 文件 Envelope.swift:

final class Envelope { let note:Note; init(_ note:Note) { self.note=note } }

Swift 文件 main.swift:

let n=Note()
let e=Envelope(n)
n.text="b"
print(e.note.text)

Swift 输出:

b

GDScript 示例文件 demo_note.gd:

class_name DemoNote
extends RefCounted
var text: String = "a"

GDScript 示例文件 demo_envelope.gd:

class_name DemoEnvelope
extends RefCounted
var note: DemoNote
func _init(value: DemoNote) -> void:
	note = value

GDScript 示例文件 main.gd:

extends Node

func _ready() -> void:
	var note: DemoNote = DemoNote.new()
	var envelope: DemoEnvelope = DemoEnvelope.new(note)
	note.text = "b"
	print(envelope.note.text)

GDScript 输出:

b
challenge icon

挑战

简单

实现 RateRule(cents:int),并提供 cost(units:int)。BillBox(rule:RateRule) 会存储传入的规则,total(units:int) 会委托该规则处理。之后更改 rule.cents 必须影响账单。Solve 使用 [rate,units]。

输入是 stdin 上的一个 JSON 数组。锁定的 main 会解析它,调用公开 API,并输出 result=,后面跟返回的文本和一个换行符。辅助函数不应输出内容。输入用例执行前,独立的固定探测会验证必需的 API 行为;它们不会强制规定实现风格。

你的代码应写在 rate_rule.gd、bill_box.gd 和 exercise.gd 中。main.gd 存放提供的输入/输出代码,不能编辑。每个 class_name 类型都要放在对应名称的文件中。

亲手试试

extends Node

func contract_ok(data: Array) -> bool:
	var rule: RateRule = RateRule.new(2)
	var bill: BillBox = BillBox.new(rule)
	rule.cents = 7
	if rule.cost(3) != 21 or bill.total(3) != 21: return false
	return true

func _ready() -> void:
	var data: Array = JSON.parse_string(OS.read_string_from_stdin())
	if not contract_ok(data):
		print("API_CONTRACT_FAILED")
		return
	print("result=" + Exercise.solve(data))
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 Swift 开发者的 GDScript中的所有课

自己练习: GDScript 在线编译器