3
4

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 5 years have passed since last update.

Optional bindingに関して

3
Last updated at Posted at 2015-10-26

Start Developing iOS Apps. optional bindingに関して

Optional Binding構文

オプショナル型は、下記のようにif文の条件で使用することができます。
値が空(nil)の場合はfalse、それ以外はtrueを返します。

嬉しい点 => nilチェックとアンラッピングができるから嬉しい
unwrap

値が空(nil)ではない事を表す。
アンラップはラップ(包装)の反対で、オプションという包装紙に包まれた変数の包装を解くイメージです。

アンラッピング 方法1

変数 = オプショナル型 <= unwrap、値が空ではない状態にする事

アンラッピング 方法2

オプショナル型の変数名の後ろに「!」マークをつける

var price: Int?
price = 300
let priceWithTax = calculateTax(price!) <=ココ

var price: Int? = 100
if let p = price {
    print("価格:\(p)円")
} else {
    print("価格:未定")
}
var price: Int? = 100

if var p = price {
    p -= 10
    print("割引価格:\(p)円")
}

参考URL
http://tea-leaves.jp/swift/content/%E3%82%AA%E3%83%97%E3%82%B7%E3%83%A7%E3%83%8A%E3%83%AB%E5%9E%8B

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?