Menu
CoddyTech

类与共享标识

Coddy 面向 C# 开发者的 Swift 课程的第 28 课,共 48 课。

C# 和 Swift 的类具有引用语义:赋值会复制引用,因此多个别名会观察到同一对象的变化。对象身份与值相等是两回事。C# 的 ReferenceEquals 用于判断引用是否指向同一个对象;Swift 使用 === 判断类实例的身份。Swift 类不会自动获得成员初始化器,因此需要声明用于设置存储属性的初始化器。如果设计中不需要继承,就将类标记为 final。示例会重命名共享文档,并将它与另一个标题相同的文档进行比较。它没有实现递增计数器。即使类绑定是常量,也仍然可以更改可变实例属性。

C#

完整的程序文件:Program.cs。

using System;
using System.Collections.Generic;
using System.Linq;
class Document { public string Title { get; set; } public Document(string title) { Title = title; } }

class Program
{
    static void Main()
    {
        var document = new Document("draft");
        var alias = document;
        alias.Title = "published";
        var other = new Document("published");
        Console.WriteLine(document.Title);
        Console.WriteLine(object.ReferenceEquals(document, other) ? "same" : "different");
    }
}

Swift

完整的程序文件:Document.swift。

final class Document { var title: String; init(title: String) { self.title = title } }

完整的程序文件:main.swift。

let document = Document(title: "draft")
let alias = document
alias.title = "published"
let other = Document(title: "published")
print(document.title)
print(document === other ? "same" : "different")
challenge icon

挑战

简单

实现 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") }
quiz icon自我测试

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

面向 C# 开发者的 Swift中的所有课

自己练习: Swift 在线编辑器