SlideShare ist ein Scribd-Unternehmen logo
1 von 42
Downloaden Sie, um offline zu lesen
制御構文1
MOBILEPROGRAMMING OCT, 10TH
テキスト
制御構文!
▸ ifやforなど分岐や繰り返し処理を特定の文に構造化したもの
▸ プログラムの構造は 順次、選択、反復の三つに分類される
▸ これらを組み合わせてプログラミングする方法を構造化プロ
グラミングと呼ぶ
▸ Swiftでは “if文” ですが 言語によっては “if式” と呼ぶこともあ
ります
▸ 今回は条件分岐の構文に絞ってやって行きます
テキスト
文?式?🤔(おまけ)
▸ 式と文の違いは 値を返すか否かです
▸ 例えば “if文” は値を返さないので右の例のようなことはでき
ません
let message = if age > 18 {
"成人です"
} else {
"未成年です"
}
let message: String
if age > 18 {
message = "成人です"
} else {
message = "未成年です"
}
文の場合 式の場合
1. IF
テキスト
IF文
▸ 条件によって処理を分岐させたいときにはifを使います
▸ 文法は
▸ if <条件式> { /* 条件が正の時 */ } else { /* 条件が負の時 */ }
▸ となります
▸ 条件が複数ある場合は else if も使えます
テキスト
例文
// 基本形
let age = 20
if age >= 20 {
print("成人してます!")
}
else {
print("未成年です")
}
// 条件が複数ある場合
if age >= 18 {
print("大学生です")
}
else if age >= 15 {
print("高校生です")
}
else if age >= 12 {
print("実は魔族だった私は中学生……少なく
}
else {
print("小学生です")
}
// elseは省略可能
if age >= 20 {
print("成人してます!")
}
SWIFTのIFは条件分
岐だけじゃない!
1-2. IF-LET
テキスト
IF-LET?🤔
▸ Optional型(Ex: Int?)から値を安全に取り出す方法
▸ Optional-binding(オプショナルバインディング)の一つ
▸ if-let 式と呼ばれる
▸ 条件分岐としてだけでなくこちらも非常によく使われる
▸ 文法は
▸ if let <変数名> = <optional> { /* not nil */ } else { /* nil */ }
テキスト
例文
// 基本形
let age: Int? = 20
if let a = age {
print("僕は (a)歳です!")
}
else {
print("年齢はありません")
}
// if-let + 条件分岐
let age: Int? = 20
if let a = age, a >= 20 {
print("僕は (a)歳で、成人してます!")
}
2. GUARD
テキスト
GUARD文
▸ Swift独自の構文
▸ 文法は guard <条件式> else { /* returnさせる */ }
▸ ifと違い条件にマッチした場合処理を進め、マッチしない場合は else のブロックの
中に入りそれ以上処理を進ませないようにします
▸ else ブロックの中には 必ず return を記述する必要があります。
▸ 条件にマッチしなかった場合にreturnさせるように処理を書くことをGuard節と言い
ます
▸ Swiftには guard という guard節専用の構文がありますが他の言語では if を使って実
現します
テキスト
例文
func forAdult(age: Int) {
guard age >= 18 else {
print("見せられないよ!")
return // これを書かないとエラー
}
print("Welcome to Underground...")
}
func forAdult(age: Int) {
if age < 18 {
print("見せられないよ!")
return
}
print("Welcome to Underground...")
}
左の二つは同じ処理をしてる
2-2. GUARD-LET
テキスト
GUARD-LET
▸ if-letと同じく guard-let式もあります
▸ 基本的にはguardと同じです
▸ 違いは nil だったら先に進ませないということくらい
▸ 文法は
▸ guard let <変数名> = <Optional> else { /* return */ }
テキスト
例文
func parseResponse(responseData: [String: Any]?) -> String? {
// check response
guard let data = responseData else {
print("response data is empty")
return nil
}
guard let id = data["id"] as? String else {
print("user id is not found.")
return nil
}
return id
}
ネットワーク経由で取得したデータをパースする
3. SWITCH
テキスト
SWITCH文
▸ ifと同じく条件分岐, optional-bindingをするときに使う
▸ 古い言語だと IntやFloatなどしか使えないがSwiftでは基本的
に何でもマッチングさせられる
▸ breakを書かなくても処理が次に移らない(fall-throughしない)
▸ 条件に合致させることをパターンマッチと呼んだりする
▸ めちゃくちゃ便利
テキスト
SWITCH文
▸ 文法は
switch <値> {
case <条件式1>:
/* 処理1 */
case <条件式2>:
/* 処理2 */
case <条件式3>:
/* 処理3 */
default:
/* それ以外 */
}
3-1. マッチング
について
3-1-1. 値マッチ
ング
テキスト
値マッチング
▸ シンプルに特定の値を指定してマッチングさせる方法
▸ Intの場合は値が 10だったら, 20だったらという形
▸ カンマで区切って複数の値を並べることもできる
let age = 20
switch age {
case 20:
print("成人です")
case 13, 14, 15:
print("中学生です")
case 12:
print("小学生です!")
default:
print("バブー!")
}
3-1-2. 範囲マッ
チング
テキスト
範囲マッチング
▸ 演算子のときに利用した 範囲演算子を利用してマッチングさせることも可能
▸ Intの場合は値が 10~20だったらという形
let age = 20
switch age {
case 16...18:
print("成人です")
case 13..<16:
print("中学生です")
case 6..<13:
print("小学生です!")
default:
print("バブー!")
}
3-1-3. タプル
マッチング
テキスト
タプル(TUPLE)?🤔
▸ Swiftで使われるデータ構造の一つ
▸ カンマで区切られたリスト
▸ Arrayとは違い複数の型を持つことができる
▸ 要素を持てる上限が決まっているため、Arrayのようには使わない
▸ ↓以下のような感じ
▸ let tuple = (10, “yuichiro”, 34.5, [“gas”, “gas”, “gas”])
▸ 先頭の要素から tuple.0, tuple.1 という形でアクセスする
▸ 要素に名前(ラベル)をつけることも可能(名前付きタプル)
▸ let tuple = (number: 10, string: “yuichiro”, float: 34.5, array: [“gas”, “gas”, “gas”])
テキスト
タプルマッチング
▸ 先ほど説明したTupleを利用してマッチングさせることも可能
▸ tupleの要素の数や値でマッチングさせる
switch user {
case let (age, name):
print("user is age: (age), name: (name)")
case (let age, "hogefuga"):
print("user is age: (age), name: hogefuga")
case (20, let name):
print("user is age: 20, name: (name)")
case (20, "hogefuga"):
print("user is age: 20, name: hogefuga")
case let (age, name, gender):
print(“マッチしません")
default:
print("something else")
}
3-1-4. ENUM
マッチング
テキスト
ENUM?🤔
▸ Swiftで使われるデータ構造の一つ
▸ 複数の値をグルーピングしておくことができる型
▸ 日本語では列挙型という
▸ 文法は enum <列挙名> { case <列挙子1>, case <列挙子2>, … }
▸ Swiftの列挙型も他の言語に比べると便利
▸ Optional型も実はクラスじゃなくてenumです
▸ 詳しくは後ほど勉強します
テキスト
ENUMマッチング
▸ 先ほど説明したenumを利用してマッチングさせることも可能
▸ enumの要素を指定してマッチングさせる
▸ 要素を指定する際には .(ドット)から始める
▸ エラー処理をenumで書くことが多い
▸ SwiftのEnumも非常に便利
▸ 長くなるので次に続きます
ENUMマッチング
enum NetworkError {
case authError
case unexpectedData
case unknownError
case nilResponse
}
switch error {
case .authError:
print("認証に失敗しました")
case .unexpectedData:
print("不正なデータです")
case .unknownError:
print("よくわかりませんがエラーです(^q^)")
case .nilResponse:
print("レスポンスが空っぽです")
case .timeout:
print("サーバーから応答がありません")
}
もう一度
enum NetworkError {
case authError
case unexpectedData
case unknownError
case nilResponse
}
switch error {
case .authError:
print("認証に失敗しました")
case .unexpectedData:
print("不正なデータです")
case .unknownError:
print("よくわかりませんがエラーです(^q^)")
case .nilResponse:
print("レスポンスが空っぽです")
case .timeout:
print("サーバーから応答がありません")
}
もう一度
enum NetworkError {
case authError
case unexpectedData
case unknownError
case nilResponse
}
switch error {
case .authError:
print("認証に失敗しました")
case .unexpectedData:
print("不正なデータです")
case .unknownError:
print("よくわかりませんがエラーです(^q^)")
case .nilResponse:
print("レスポンスが空っぽです")
case .timeout:
print("サーバーから応答がありません")
}
defaultがない!
DEFAULTがない!😨(二度目)
テキスト
DEFAULTが(RY😨
▸ enumマッチングの場合はdefaultは書かなくても良い(場合
がある)
▸ enumの要素全てを指定している場合は省略可能
▸ enumの場合必ず指定された値しかこないことが保証される
のでdefaultはいらない
3-1-5. OPTIONAL
マッチング
テキスト
OPTIONALマッチング
▸ Optional型(?型)を使用してマッチングさせる
▸ 形はenumに似ている
▸ 要素は some(value) か none のみ
▸ 値があったとき、無かったときで明確に処理を分けたい場合はif-letよりもこちらを推奨
let brain: Brain? = nil
switch brain {
case .some(let brain):
print("正常です")
case .none:
print("頭空っぽ!🤯")
}
3-1-5. TYPE-CAST
マッチング
テキスト
TYPE-CASTマッチング
▸ 型変換を使うもしくは特定の型を指定してマッチングさせるやり方
▸ 型変換を使う際は “as", 型を指定したい場合は “is” を使う
▸ できれば型変換を行うコードがないのが理想ではあるので使うことは
少ない(かも?)
let nyantyu: Animal = Cat(name: "nantyu")
switch nyantyu {
case let a as Cat:
print("猫でした(?)")
a.burk()
case is Dog:
print("犬です")
default:
print("動物ではありません")
}
3-2. SWITCHのオーバー
ロードについて
テキスト
SWITCHのオーバーロード?🤯
▸ case <条件式>:
▸ ↑の部分は挙動を書き換えることが可能!
▸ 対応する演算子は =~
▸ 自分で作ったクラスを好きなようにマッチングさせること
ができるようになる

Weitere ähnliche Inhalte

Empfohlen

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Empfohlen (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Mobile programming seigyokoubun