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