LoginSignup
7
7

More than 5 years have passed since last update.

Xcode6-beta4での@IBOutletなプロパティの定義方法

Posted at

Xcode6-beta4では@IBOutletなプロパティについての仕様が変更され、以前の記述のままではnon-optional typeであるというエラーになるようになりました。これはbeta3までは@IBOutletを付けたプロパティは自動的に「weakでimplicitly unwrapped optionalなタイプで初期値はnil」に変換されていたのが、beta4の改定でこの特別扱いがなくなったからのようです。

この自動変換については以前の「Using Swift with Cocoa and Objective-C」に記述がありました(今は改定されてなくなっています)。

When you declare an outlet in Swift, the compiler automatically converts the type to a weak implicitly unwrapped optional and assigns it an initial value of nil. In effect, the compiler replaces @IBOutlet var name: Type with @IBOutlet weak var name: Type! = nil.

optionalではない型は初期化が必須なはずなのに@IBOutletを付けるとなぜか何も言われなくなるという不思議はこのためだったわけです。

今後どのようにすれば良いのかは改定後の「Using Swift with Cocoa and Objective-C」の「Working with Outlets and Actions」に記述があります。

When you declare an outlet in Swift, you should make the type of the outlet an implicitly unwrapped optional.

要は自動で変換されていた時のimplicitly unwrapped optionalにしろというだけのようです。

自動変換では更にweakで初期値がnilだったわけですが、weakについては必要かどうか判断して適宜つけるということなのではないかと思います。Release Notesの「Important Changes, Issues Resolved in Xcode 6 Beta 1 - 3」に以下のようにstrongで上書きできるようにしたという記述があるためstrongにすべき場合があるようです。

• @IBOutlets may be explicitly marked strong to override their implicitly-weak behavior. (16954464)

と思ったら

ここまで書いて改めて「Using Swift with Cocoa and Objective-C」を確認したら元の記述に戻っていました。なぜ……

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