0
1

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.

忘備録-Swiftのオプショナル型

Last updated at Posted at 2019-12-04

趣味でIOSアプリ開発をかじっていた自分が、改めてSwiftを勉強し始めた際に、曖昧に理解していたところや知らなかったところをメモしています。

参考文献

この記事は以下の書籍の情報を参考にして執筆しました。

if-let文

if-letでunwrapするときに複数の変数を指定できる

var hoge: String? = "hoge"
var fuga: String? = "fuga"
if let h = hoge, let f = fuga {
    print("nilじゃないよ")
}

guard文

guardの後に宣言した条件を満たさない場合、else節の処理を実行

func hogehoge() {
    //let hoge: String? = "hoge"
    let hoge: String? = nil
    guard hoge == nil else{
        //guardの条件じゃ無いなら下記の文が実行される。この場合nilじゃ無いなら実行
        print(hoge!)
        return
    }
    print(hoge)    //nil
    return
}
hogehoge()

nil合体演算子

ある変数がnilだった場合に別の値をセットしたいとき

let hoge: String? = nil
print(hoge ?? "hogehoge")    //hogeの値がnilなら"hogehoge"を使う

有値オプショナル型

let hoge: String! = "hoge"
let fuga: String? = "fuga"
let message1:String = hoge
let message2:String = fuga    // error unwrapしないといけない

有値オプショナル型はコンパイラが値の評価の時に特別扱いするだけで、オプショナル型と変わらない。

let message3:String! = fuga
let message4:String? = hoge

失敗のあるイニシャライザ

初期化に失敗した場合return nilをして処理を修了できる。

struct Hoge {
    var hoge: String
    init?(hoge: String?) {
        guard let h = hoge else{
        return nil
        }
    self.hoge = h
    }
}
let fuga = Hoge(hoge: nil)
if let f = fuga{
  print(fuga!.hoge)
} else {
  print(fuga)    // nil
}
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?