LoginSignup
3
3

More than 5 years have passed since last update.

class 初期化時に特定の条件でクラッシュ

Last updated at Posted at 2014-06-12

[追記] コメント欄で頂いた様に、playground 以外では正常に動作する事から、playground のバグの可能性が高そうです。

落ちないケース

class Foo {
    var array :String[]

    init() {
        array = ["bar"]
    }
}

var foo :Foo? = Foo()   // {["bar"]}

落ちるケース

class Foo {
    var dict = Dictionary<String, String>()

    init() {
        dict = ["bar":"baz"]
    }
}

var foo :Foo? = Foo()   // {["bar", "baz"]}

以下の条件で必ず落ちる

  • プロパティに Dictionary を持つ
  • 生成したクラスを代入する変数の型を、クラス型 + ? (OptionalValue) とする

経緯

abstract factory パターンを実装していて、factoryメソッドが nil もしくは Fooクラスを返却するという処理を書いており、factoryメソッドの戻り型を Foo? と定義した。上記例は余計なロジックを排除した再現コード。

疑問

そもそもクラスに ? を付ける方法が適切かどうかが確認できていないが、warning も出ないし、プロパティがディクショナリ以外であれば問題無く動作する。ディクショナリのみ落ちるロジックが知りたい。

どなたか説明付く方ご教示頂ければ幸いです。

3
3
4

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
3
3