クラスとアイデンティティの共有
Coddyの「C++開発者のためのSwift」コースのレッスン 28/48。
C++のクラス変数は独立したオブジェクトを直接保持できるため、クラス構文単体では参照セマンティクスを意味しません。このソースコードでは、エイリアス間で1つの Document インスタンスを共有するために、意図的に shared_ptr を使用しています。Swiftのクラスは常に参照アイデンティティを提供し、=== で参照が同じインスタンスを指しているかをテストします。フィールドの内容が同一であっても、そのアイデンティティを意味するわけではありません。const shared_ptr 自体がその参照先を const にするわけではありません。同様に、Swiftの let クラス参照は、許可されたメソッドやプロパティを通じてインスタンスの状態を変更できます。Swiftのクラスは、構造体のように自動的にすべてのメンバーワイズイニシャライザを受け取るわけではないため、適切なイニシャライザが必要です。オブジェクトモデルを移植・設計する際は、ストレージと所有権を明示的に選択してください。
C++
完全なプログラムファイル:main.cpp。
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <optional>
#include <memory>
#include <tuple>
#include <variant>
#include <stdexcept>
#include <algorithm>
struct Document { std::string title; };
int main() {
auto document = std::make_shared<Document>(Document{"draft"});
auto alias = document;
alias->title = "published";
auto other = std::make_shared<Document>(Document{"published"});
std::cout << document->title << '\n';
std::cout << (document == other ? "same" : "different") << '\n';
}
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")チャレンジ
簡単init(_ value: Int)、呼び出し元に対して読み取り専用のvalue、および 1 を加算する increment() を持つ参照型である Counter を実装してください。入力は -100 から 100 までの初期値と、それに続く 0 から 20 までの回数です。カウンターのエイリアスを作成し、そのエイリアス経由で指定された回数分インクリメントを行い、元の値を出力してください。
必要な API と solve(_ input: String) -> String を実装してください。末尾に改行を含めずに出力テキストを返してください。編集可能なコード内で標準出力を行わないでください。ロックされたドライバーは、追加の有効な入力で独自に API を検証し、返されたテキストを正確に 1 つの改行とともに出力します。すべての数値演算は 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プレイグラウンド