LoginSignup
12
11

More than 5 years have passed since last update.

nullable, nonnullを明記することで幸せになる

Last updated at Posted at 2016-08-01

nullable

Objective-Cのプロパティなどはこれに値している。
プロパティの中身が nil であっても良いという場合のことが相当する。

Objective-Cで nullable を指定しておくことで、SwiftでOptionalとして使用することが可能になる。

nullableサンプル
@interface Sample()

@property (nullable, nonatomic) NSString *text;

@end

また、以下のようにすることで...

Objective-Cメソッドサンプル
@interface Sample : NSObject

- (nullable UIImage *)getHanayoKoizumi;

@end

メソッドの戻り値にも nullable を指定することでSwift側からのアクセスで強制アンラップをしない幸せなことが起こる!

Swiftメソッドサンプル
func getHanayoKoizumi() -> UIImage?

nonnull

プロパティなどの中身が nil を許容しない場合にしようする。
また、 nonnull を明記することでOptionalではないことを表すことになります。

NS_ASSUME_NONNULL_BEGIN から NS_ASSUME_NONNULL_END を使うことでその間にあるものをすべて nonnull 属性を与えることができます。
また、この間でも nullable を指定しているものに関しては nullable として扱うことができます。

nonnullサンプル
@interface Sample ()

@property (nonatomic) NSString *text;

@end
12
11
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
12
11