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

Swift パターンマッチ

Posted at

通常Switch文で使用されると思われるパターンマッチだがifguardwhileにも使用される

if

 let age = 8
 if case 1...12 = age {
 print("小学生です")
}

switch文では条件をすべて網羅しつつ、できないものはdefaultで拾う書き方をするがif文では網羅する必要がない際に使われる。

guard

 let age = 23
 guard case 1...20 = age else {
   return 
 } 
print("二十歳以下です")
}

while

パターンに合うまではその処理を繰り返し回す。

 var nextAge = Optional(1)
 while case let age? = nextAge {
 if age >= 20 {
   nextAge = nil
  } else {
   nextAge += 1
 }
}
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?