SlideShare a Scribd company logo
1 of 29
Download to read offline
Swiftをキめると
気持ちいい!
AKIBA.swift #04
About Me
• 田中 孝明 (Takaaki Tanaka)
• クラスメソッド株式会社
• @kongmingtrap
• iOS Developer (Swift / Objective-C)
• GyazSquare / GitHub
皆様
Swift 書いていますか?
Objective-Cから入ってきた方々
ツラくないですか?
僕はツラかったです。
それから。。。色々あり。。。
便利な関数を使って
簡潔に書くようにすることで
書くのが楽しくなってきました。
便利な関数
• forEach
• map
• reduce
• filter
• flatmap
便利な関数
• forEach
• map
• reduce
• filter
• flatmap
map / flatmap
• Optional
• SequenceType
• Collection
• FlatMap
適用されている者たち
map / flatmap
public func map<U>(
_ transform: @noescape (Wrapped) throws -> U
) rethrows -> U? {
switch self {
case .some(let y):
return .some(try transform(y))
case .none:
return .none
}
}
細かい説明は省いて後にして使ってみよう
map / flatMapで
動作を比べてみる
Example
enum PokemonType: String {
case Grass = "Grass"
case Water = "Water"
case Fire = "Fire"
case Electric = "Electric"
}
ある時こんなEnumがおりました。
Sequence
let types = ["Grass", "Water", "Fire", "Electric"]
let pokemonTypes =
types.map { PokemonType(rawValue: $0) }
[Optional(PokemonType.Grass), Optional(PokemonType.Water),
Optional(PokemonType.Fire), Optional(PokemonType.Electric)]
結果がOptionalになる
Sequence
let types = ["Grass", "Water", "Fire", "Electric"]
let pokemonTypes =
types.flatMap { PokemonType(rawValue: $0) }
[PokemonType.Grass, PokemonType.Water,
PokemonType.Fire, PokemonType.Electric]
結果がunwrapされる
Sequence
let types = ["Grass", "Water", "Fire", "Ice"]
let pokemonTypes =
types.map { PokemonType(rawValue: $0) }
[Optional(PokemonType.Grass), Optional(PokemonType.Water),
Optional(PokemonType.Fire), nil]
愚直に結果を返す
Sequence
let types = ["Grass", "Water", "Fire", "Ice"]
let pokemonTypes =
types.flatMap { PokemonType(rawValue: $0) }
[PokemonType.Grass, PokemonType.Water,
PokemonType.Fire]
結果がunwrapされ、nilが打ち消される
Collection
let types1 = ["Electric", "Electric", "Fire"]
let types2 = ["Water", "Ice"]
let types3 = ["Fire", "Grass", "Rock", "Grass"]
let types = [types1, types2, types3].map { $0 }
[["Electric", "Electric", "Fire"], ["Water", "Ice"],
["Fire", "Grass", "Rock", "Grass"]]
Collection
let types1 = ["Electric", "Electric", "Fire"]
let types2 = ["Water", "Ice"]
let types3 = ["Fire", "Grass", "Rock", "Grass"]
let types = [types1, types2, types3].flatMap { $0 }
["Electric", "Electric", "Fire", "Water", "Ice",
"Fire", "Grass", "Rock", "Grass"]
結果がflatなArrayになる
Collection
let types1 = ["Electric", "Electric", "Fire"]
let types2 = ["Water", "Ice"]
let types3 = ["Fire", "Grass", "Rock", "Grass"]
let types = [types1, types2, types3].flatMap
{ $0 }.flatMap { PokemonType(rawValue: $0) }
[PokemonType.Electric, PokemonType.Electric, PokemonType.Fire,
PokemonType.Water, PokemonType.Fire, PokemonType.Grass, PokemonType.Grass]
nilが打ち消されるため、欲しいデータだけ残る
Optional
let value: String? = "Fire"
let value1 = value.map { PokemonType(rawValue: $0) }
Optional(Optional(PokemonType.Fire))
結果が二重のOptionalになる
Optional
let value: String? = "Fire"
let value1 = value.flatMap { PokemonType(rawValue:
$0) }
Optional(PokemonType.Fire)
結果のOptionalが打ち消される(unwrapされる)
Optional
let type = PokemonType(rawValue: "Water")
let changedType = pokemon.map { type -> PokemonType in
switch type {
case .Water:
return PokemonType.Electric
default:
return type
}
}
Optional(PokemonType.Electric)
unwrapして値を取り扱う
Optional
let value1: Int? = 10
let value2: Int? = 20
let value = value1.flatMap {
v1 in value2.map { v2 in v1 + v2 } }
Optional(30)
Optional同士の値の計算
まとめ
• 簡潔に書こう
• Optionalと仲良く付き合おう
• Playgroundを有効活用しよう
Thank You !!!

More Related Content

Similar to Swiftをキめると 気持ちいい!

From Lisp to Clojure/Incanter and RAn Introduction
From Lisp to Clojure/Incanter and RAn IntroductionFrom Lisp to Clojure/Incanter and RAn Introduction
From Lisp to Clojure/Incanter and RAn Introduction
elliando dias
 
Os Fetterupdated
Os FetterupdatedOs Fetterupdated
Os Fetterupdated
oscon2007
 
A little bit of clojure
A little bit of clojureA little bit of clojure
A little bit of clojure
Ben Stopford
 
Five Languages in a Moment
Five Languages in a MomentFive Languages in a Moment
Five Languages in a Moment
Sergio Gil
 
楽々Scalaプログラミング
楽々Scalaプログラミング楽々Scalaプログラミング
楽々Scalaプログラミング
Tomoharu ASAMI
 
Fertile Ground: The Roots of Clojure
Fertile Ground: The Roots of ClojureFertile Ground: The Roots of Clojure
Fertile Ground: The Roots of Clojure
Mike Fogus
 

Similar to Swiftをキめると 気持ちいい! (18)

Coscup2021-rust-toturial
Coscup2021-rust-toturialCoscup2021-rust-toturial
Coscup2021-rust-toturial
 
Introduction to Functional Programming with Haskell and JavaScript
Introduction to Functional Programming with Haskell and JavaScriptIntroduction to Functional Programming with Haskell and JavaScript
Introduction to Functional Programming with Haskell and JavaScript
 
From Lisp to Clojure/Incanter and RAn Introduction
From Lisp to Clojure/Incanter and RAn IntroductionFrom Lisp to Clojure/Incanter and RAn Introduction
From Lisp to Clojure/Incanter and RAn Introduction
 
TRICK 2018 results
TRICK 2018 resultsTRICK 2018 results
TRICK 2018 results
 
Os Fetterupdated
Os FetterupdatedOs Fetterupdated
Os Fetterupdated
 
A little bit of clojure
A little bit of clojureA little bit of clojure
A little bit of clojure
 
Five Languages in a Moment
Five Languages in a MomentFive Languages in a Moment
Five Languages in a Moment
 
Learning Content Patterns from Linked Data
Learning Content Patterns from Linked DataLearning Content Patterns from Linked Data
Learning Content Patterns from Linked Data
 
Why is Haskell so hard! (And how to deal with it?)
Why is Haskell so hard! (And how to deal with it?)Why is Haskell so hard! (And how to deal with it?)
Why is Haskell so hard! (And how to deal with it?)
 
楽々Scalaプログラミング
楽々Scalaプログラミング楽々Scalaプログラミング
楽々Scalaプログラミング
 
A Scala Corrections Library
A Scala Corrections LibraryA Scala Corrections Library
A Scala Corrections Library
 
Speaking Scala: Refactoring for Fun and Profit (Workshop)
Speaking Scala: Refactoring for Fun and Profit (Workshop)Speaking Scala: Refactoring for Fun and Profit (Workshop)
Speaking Scala: Refactoring for Fun and Profit (Workshop)
 
Idioms in swift 2016 05c
Idioms in swift 2016 05cIdioms in swift 2016 05c
Idioms in swift 2016 05c
 
Fertile Ground: The Roots of Clojure
Fertile Ground: The Roots of ClojureFertile Ground: The Roots of Clojure
Fertile Ground: The Roots of Clojure
 
From Java To Clojure (English version)
From Java To Clojure (English version)From Java To Clojure (English version)
From Java To Clojure (English version)
 
Esoteric, Obfuscated, Artistic Programming in Ruby
Esoteric, Obfuscated, Artistic Programming in RubyEsoteric, Obfuscated, Artistic Programming in Ruby
Esoteric, Obfuscated, Artistic Programming in Ruby
 
And now you have two problems. Ruby regular expressions for fun and profit by...
And now you have two problems. Ruby regular expressions for fun and profit by...And now you have two problems. Ruby regular expressions for fun and profit by...
And now you have two problems. Ruby regular expressions for fun and profit by...
 
Introduction to Perl Best Practices
Introduction to Perl Best PracticesIntroduction to Perl Best Practices
Introduction to Perl Best Practices
 

More from Takaaki Tanaka (6)

Server Side? Swift
Server Side? SwiftServer Side? Swift
Server Side? Swift
 
Enumはデキる子 ~ case .Success(let value): ~
 Enumはデキる子 ~ case .Success(let value): ~ Enumはデキる子 ~ case .Success(let value): ~
Enumはデキる子 ~ case .Success(let value): ~
 
全部見せます!最前線エンジニアが語るBleアプリケーションのハマりどころ(i os)
全部見せます!最前線エンジニアが語るBleアプリケーションのハマりどころ(i os)全部見せます!最前線エンジニアが語るBleアプリケーションのハマりどころ(i os)
全部見せます!最前線エンジニアが語るBleアプリケーションのハマりどころ(i os)
 
Swift api design guidelines (dec 3, 2015)
Swift api design guidelines (dec 3, 2015)Swift api design guidelines (dec 3, 2015)
Swift api design guidelines (dec 3, 2015)
 
モバイル開発者から見た サーバーレスアーキテクチャ
モバイル開発者から見た サーバーレスアーキテクチャモバイル開発者から見た サーバーレスアーキテクチャ
モバイル開発者から見た サーバーレスアーキテクチャ
 
AddressBook to Contacts
AddressBook to ContactsAddressBook to Contacts
AddressBook to Contacts
 

Recently uploaded

Recently uploaded (20)

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 

Swiftをキめると 気持ちいい!