类与共享标识
Coddy 面向 C 开发者的 Swift 课程的第 28 课,共 48 课。
C 指针可以为同一个结构体对象创建别名,而 Swift 类提供语言级别的引用身份和由 ARC 管理的生命周期。赋值 Swift 类引用会共享同一个实例。Swift 的 === 用于检查身份,而 == 取决于适用的相等性一致性,并非总是检查身份。
两个示例都通过第二个引用关闭同一份文档。这里的 C 对象具有自动存储期,在整个访问过程中都有效。Swift 的 let 会阻止重新绑定类引用,但仍允许方法更改可变的实例状态。必须分别考虑 C 指针的 const 性和指向对象的 const 性。
C:完整程序
document.h
#ifndef DOCUMENT_H
#define DOCUMENT_H
#include <stdbool.h>
typedef struct { bool open; } Document;
static void document_close(Document *document) { document->open = false; }
#endif
main.c
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include "document.h"
int main(void) {
Document document = {true};
Document *first = &document;
Document *second = first;
document_close(second);
printf("%s %s\n", first->open ? "true" : "false", first == second ? "true" : "false");
return 0;
}
Swift:完整程序
Document.swift
import Foundation
final class Document {
private(set) var open = true
func close() { open = false }
}main.swift
import Foundation
let first = Document()
let second = first
second.close()
print("\(first.open) \(first === second)")固定的 Swift 类绑定并不意味着深度不可变。另一个引用可以更改同一个实例,其观察者也会看到结果。
挑战
简单实现 Counter,这是一个引用类型,包含 init(_ value: Int)、仅对调用方可读的 value,以及将值加一的 increment()。输入依次为初始值(-100 到 100)和计数(0 到 20)。为计数器创建一个别名,通过该别名递增计数次,并输出原始值。
实现所需的 API 和 solve(_ input: String) -> String。返回不带末尾换行符的输出文本;不要在可编辑代码中打印。锁定的驱动程序会使用其他有效输入独立检查这些 API,然后将返回的文本打印出来,并且只添加一个换行符。所有数值运算都不会超出 Int 的范围。
你的代码应放在 Counter.swift 和 Functions.swift 中。main.swift 包含提供的输入/输出代码,不能编辑。
亲手试试
import Foundation
func apiChecks(_ input: String) -> Bool {
let a = Counter(5); let alias = a; let separate = Counter(5); alias.increment(); alias.increment(); return a === alias && a.value == 7 && separate.value == 5
}
let input = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8)!
// 开始公开 API 检查
let apiOK = apiChecks(input)
// 结束公开 API 检查
if apiOK { print(solve(input)) } else { print("API mismatch") }
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C 开发者的 Swift中的所有课
自己练习: Swift 在线编辑器