0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

init?とは 失敗可能イニシャライザ

Last updated at Posted at 2021-02-07

実行環境

Xcode 12.2
Swift 5.3.1

失敗可能イニシャライザ

失敗可能イニシャライザとは、初期化に失敗する可能性があるプロパティを初期化するときに使えるものです。
init?(引数)と記述し、失敗時にはnilを返します。

具体例を見ていきましょう。

記述例

    
class TestFailInit {
    var num1: Any
    var num2: Any
    
    init?(_ num1: Any, _ num2: Any) {
        guard let num1 = num1 as? Int, let num2 = num2 as? Int else {return nil}
        
        self.num1 = num1
        self.num2 = num2
    }

こちらはnum1とnum2というAny型のプロパティを初期化時にInt型にダウンキャストするというものです。

しかし、引数によってはダウンキャストに失敗する可能性もあります。

このように初期化時に失敗する可能性があるときは失敗可能イニシャライザを使います。失敗時はreturn nilし、プロパティは未初期化状態となります。

if TestFailInit("テスト",5) != nil {
    // ダウンキャストに成功しているため
    print("初期化成功")
} else {
    // ダウンキャストに失敗しているため
    print("初期化失敗") // 初期化失敗
}

実際先ほどのものを初期化してみます。

こちらは引数にString型を取っているのでInt型にキャストできないですね。つまりreturn nilとなり、「初期化失敗」とプリントされます。

参考文献

石川洋資 / 西山勇世
[増補改訂第3版]Swift実践入門 ── 直感的な文法と安全性を兼ね備えた言語

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?