LoginSignup
0
2

More than 5 years have passed since last update.

Swift イニシャライザ

Last updated at Posted at 2018-11-09

イニシャライザとは

型のインスタンス化を初期化する
すべてのプロパティはインスタンス化の完了までに値が代入されていなければならないため、プロパティの宣言時に初期値を持たないプロパティはイニシャライザ内で初期化する必要がある。

定義方法

initキーワードで宣言し、引数と初期化に関する処理を定義する。


init(引数){
   初期化処理
}

次の例では、selfIntroduction型に定義したイニシャライザを用いて、selfIntroduction型のインスタンスを初期化している。


struct selfIntroduction {
    var name: String
    var age: Int

    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
}

var val = selfIntroduction(name: "kunio", age: 21)
print(val.name)
print(val.age)

すべての型に共通のイニシャライザ

失敗可能イニシャライザ

  • 初期化の失敗を考慮したイニシャライザ
  • 戻り値はOptional型(初期化に失敗した場合にnilを返す)

失敗可能イニシャライザはinitキーワードに?を加えてinit?(引数)のように定義する。
初期化の失敗はreturn nilで表し、イニシャライザはnilを返す。


struct Item {
    let id: Int
    let title: String

    init?(dictionary: [String: Any]) {
        guard let id = dictionary["id"] as? Int,
        let title = dictionary["title"] as? String else {
            return nil
        }
        self.id = id
        self.title = title
    }
}

let dictionaries: [[String: Any]] = [
    ["id": 1, "title": "ABC"],
    ["id": 2, "title": "DEF"],
    ["id": 3, "title": "GHI"],
    ["title": "JKL"]
]

for dictionary in dictionaries {
    if let item = Item(dictionary: dictionary) {
        print(item)
    } else {
        print("エラー: \(dictionary)")
    }
}

随時更新

0
2
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
0
2