Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

More than 5 years have passed since last update.

[Swift言語を学ぶ]構造体

Posted at

カプセル化を実現する方法としてSwiftには、クラスの他に構造体(struct)が用意されています。但し、クラスと構造体には次のような違いがあります。

  • 構造体では継承は利用できません。
  • 構造体にデイニシャライザは定義できません。
  • クラスのインスタンスを別の変数に代入すると参照が渡されます。インスタンスの参照数は参照カウントで管理されます。対して構造体を別の変数に代入すると新たなコピーが生成されます。構造体の参照先は常に1つなので参照カウントは使用されません。

構造体の書き方はクラスとよく似ています。

import Foundation

/// 著者
struct Author {
    var name: String = "不明"
    var birthday: Date?   // DateはCocoaフレームワークの日付型。りようするためには「import Foundation」が必要
}

let author = Author()

イニシャライザを使ってメンバ変数を初期化することもできます。

/// 著者
struct Author {
    var name: String
    var birthday: Date?
    init() {
        name = "不明"
    }
}

let author = Author()

また、構造体はメンバ変数を引数にもつイニシャライザが自動的に生成されるため、イニシャライザを自前で用意しなくても次のように初期化することができます。

/// 著者
struct Author {
    var name: String
    var birthday: Date?
}

let formatter = DateFormatter()
formatter.dateFormat = "Y/M/d"
let author = Author(name: "夏目漱石", birthday: formatter.date(from: "1867/2/9"))

プロパティへのアクセスはクラスの場合と同様、.(ドット)を使います。

var author = Author(name: "夏目漱石", birthday: formatter.date(from: "1867/2/9"))
print("著者:" + author.name)   // 著者:夏目漱石

author.name = "森鴎外"
author.birthday = formatter.date(from: "1862/2/17")
print("著者:" + author.name)   // 著者:森鴎外

構造体のメンバに構造体が含まれる場合は次の様に.(ドット)で繋いでアクセスします。

/// 著者
struct Author {
    var name: String = "不明"
    var birthday: Date?
}

/// 書籍
struct Book {
    var title: String
    var author: Author
}

let formatter = DateFormatter()
formatter.dateFormat = "Y/M/d"

let book = Book(
    title: "吾輩は猫である",
    author: Author(name: "夏目漱石", birthday: formatter.date(from: "1867/2/9"))
)

print("書籍名:\(book.title), 著者:\(book.author.name)")    // 書籍名:吾輩は猫である, 著者:夏目漱石

定数として宣言した構造体のプロパティを変更することはできません。

let author = Author(name: "夏目漱石", birthday: formatter.date(from: "1867/2/9"))
author.name = "森鴎外" // エラー(変更できない)

構造体は変数へ代入される時にプロパティも含めてコピーされます。別の変数に代入した構造体のプロパティを変更しても、元の構造体のプロパティの値は変わりません。
参照が代入され同じインスタンスを複数の変数で共有するクラスの場合とは動作が異なります。

let author = Author(name: "夏目漱石", birthday: formatter.date(from: "1867/2/9"))
var book1 = Book(title: "坊ちゃん", author: author)
var book2 = book1
book2.title = "吾輩は猫である"

print(book1.title)    // 坊ちゃん
print(book2.title)    // 我が輩は猫である

:exclamation: SwiftのString、Array、Dictionaryは、構造体を使って実装されています。つまり、これらを他の変数に代入したり、関数の引数として渡す時には、値がコピーされます。クラスとして実装されているCocoaのNSString、NSArray、NSDictionaryとはこの辺の動作が異なっています。
但し、Swiftのこれらのインスタンスのコピーも、実際に必要になった時点(コピー先のプロパティが実際に変更された時等)でコビーされるようにコンパイラが最適化してくれるので、オーバーヘッドについて過剰に心配する必要はありません。

0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?