Help us understand the problem. What is going on with this article?

swift optional型 調べてみた

More than 5 years have passed since last update.

optional型はnilが入ることができる
optional型の初期値はnil
optional型は非optional型とは同じようには扱えない(IntとInt?は全くの別物)

ラップ、アンラップの4つの方法

1(ラップ) !をつける(nilが入るとエラー)

2(ラップ) ?をつける(nilが入っていると、nilが返ってくる)

class Dog {
    func bark() -> String {
        return "Wan!"
    }
}

var d: Dog? = Dog() // Optional型

// 変数dのうしろに、「?」を付けるとアンラップされる(Optional Chaining)
println(d?.bark()) // -> Wan!

// 変数dにnilが入っていた場合、アンラップ時にnilが返ってくる
d = nil
println(d?.bark()) // -> nil

3 ifやwhileの条件式で宣言され、optional型の変数を代入された時は非optional型になる

class Dog{
    func bark() ->{
        return "wan"
    }
}

var wrappedDog: Dog? = Dog()  //optional型

//非optional型になる
if var unwrapped = wrappedDog {
    println(unwrapped.bark())
}

ただし。if文内のみで有効

4(アンラップ) 暗黙的アンラップ(Implicity unwrapped Optional)

?ではなく!を使ってラップする
アンラップ操作は不要(暗黙的にアンラップされる)

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした