SlideShare ist ein Scribd-Unternehmen logo
1 von 51
Downloaden Sie, um offline zu lesen
Idioms in Swift
Kaz Yoshikawa
May 2016
About me
Kaz Yoshikawa
• Electricwoods LLC 代表 / Digital Lynx Systems Inc. 副代表
• e-mail: kaz@digitallynx.com
• LinkedIn: https://www.linkedin.com/in/kazyoshikawa
• Working History
• Adobe Systems (Tokyo)
• Lionbridge (Tokyo)
• Quark (Tokyo / Denver)
• Hummingbird Communications (Mt. View, USA)
• Fact International (Vancouver, Canada)
• Perle Systems (Toronto, Canada), etc.
Engineering
将棋盤Kit
What is Idiom?
Optional
guard let
• 二つの引数が nil でない事を保証する
func add(a: Int?, _ b: Int?) -> Int? {
guard let a = a, let b = b else { return nil }
return a + b
}
if let
• if let を使う
func add(a: Int?, _ b: Int?) -> Int? {
if let a = a, let b = b {
return a + b
}
return nil
}
where
• guard let で0以上を保証する
func add(a: Int?, _ b: Int?) -> Int? {
guard let a = a, let b = b where a >= 0 && b >= 0 else {
return nil
}
return a + b
}
• if let でも0以上を保証する
func add(a: Int?, _ b: Int?) -> Int? {
if let a = a, let b = b where a >= 0 && b >= 0 {
return a + b
}
return nil
}
nil-coalescing Operator
• nil の場合は 0 として扱う
func add(a: Int?, b: Int?) -> Int {
return (a ?? 0) + (b ?? 0)
}
Switch
Optional in Switch
• 実は optional も switch 文に使える
func countryName(identifier: String?) -> String? {
switch identifier {
case "JP"?: return "Japan"
case "GB"?: return "England"
case "US"?: return "U.S.A."
default: return nil
}
}
Late Initializing

Immutable Variables
• 初期値を後で設定する不定変数
let color: UIColor // "= value"
switch value % 3 {
case 0: color = UIColor.whiteColor()
case 1: color = UIColor.redColor()
default: fatalError()
}
• 初期化しないケースがあると、コンパイルエラー
Complex switch cases
for thing in things {
switch thing {
case 0 as Int:
print("zero as an Int")
case 0 as Double:
print("zero as a Double")
case let someInt as Int:
print("an integer value of (someInt)")
case let someDouble as Double where someDouble > 0:
print("a positive double value of (someDouble)")
case is Double:
print("some other double value")
case let someString as String:
print("a string value of "(someString)"")
case let (x, y) as (Double, Double):
print("an (x, y) point at (x), (y)")
case let movie as Movie:
print("Movie:'(movie.name)'")
default:
print("something else")
}
}
Implicitly
Unwrapped Optional
Implicitly Unwrapped
Optional with if statement
• Implicitly Unwrapped Optional でも if let は 使える
let a: Int!



if let a = a {
print("(a)")
}
Implicitly Unwrapped Optional
with guard statement
• Implicitly Unwrapped Optional でも guard は 使える
class MyObject {
var value: Int! = nil
func some() {
guard let value = value else { return }
print("(value)")
}
func other() {
guard value != nil else { return }
print("(value)")
}
}
Associated Values
Defining Associated
Value
enum Element {
case String(Swift.String)
case Boolean(Bool)
case Integer(Int)
case Float(Swift.Float)
case Dictionary([Swift.String: Element])
case Array([Element])
case Null
}
let integer = Element.Integer(42)
let city = Element.String("Tokyo")
let cities = Element.Array([city])
let dictionary = Element.Dictionary(["items": array])
Extracting Associated Values
Using switch Statement
• Associated Value を Switch文で取り出す
switch element {
case .String(let string): print("string: (string)")
case .Boolean(let value): print("boolean: (value)")
case .Integer(let value): print("ineteger: (value)")
case .Float(let value): print("float: (value)")
case .Dictionary(let dictionary):
print("dictionary: (dictionary)")
case .Array(let array): print("array: (array)")
case .Null: print("null")
}
Extracting Associated
Values using if Statement
• If 文でも取り出せます
let element1: Element = …
if case .String(let string) = element1 {
print("(string)")
}
• Optional な場合でも取り出せます
let element: Element? = …
if case .String(let string)? = element1 {
print("(string)")
}
Extracting Associated
Values
• division -> members -> person -> name
let name = Element.String("John")
let john = Element.Dictionary(["name": name])
let members = Element.Array([john])
let group = Element.Dictionary(["members": members])
• 一発で取り出せる
if case .Dictionary(let group) = group,
case .Array(let members)? = division["members"],
case .Dictionary(let member)? = members.first,
case .String(let name)? = member["name"] {
print("(name)") // John
}
Closure
Basic Closure
class MyViewController: UIViewController {
var state: Bool = false
func toggle(animated: Bool) {
let closure = {
self.view.backgroundColor = self.state ?
UIColor.redColor() : UIColor.whiteColor()
self.state = !self.state
}
if animated {
UIView.animateWithDuration(0.3) {
closure() // <-- Here!!
}
}
else {
closure() // <-- Here!!
}
}
}
Basic Closure
class MyViewController: UIViewController {
var state: Bool = false
func toggle(animated: Bool) {
let closure = {
self.view.backgroundColor = self.state ?
UIColor.redColor() : UIColor.whiteColor()
self.state = !self.state
}
if animated {
UIView.animateWithDuration(0.3) {
closure() // <-- Here!!
}
}
else {
closure() // <-- Here!!
}
}
}
Execute on Main Thread
func dispatch_sync_main(block: () -> Void) {
if NSThread.isMainThread() {
block()
}
else {
dispatch_sync(dispatch_get_main_queue()) { () ->
Void in
block()
}
}
}
dispatch_sync_main {
self.tableView.reloadData()
}
Execute on Main Thread
func dispatch_sync_main(block: () -> Void) {
if NSThread.isMainThread() {
block()
}
else {
dispatch_sync(dispatch_get_main_queue()) { () ->
Void in
block()
}
}
}
dispatch_sync_main {
self.tableView.reloadData()
}
Execute on Main Thread
func dispatch_sync_main(block: () -> Void) {
if NSThread.isMainThread() {
block()
}
else {
dispatch_sync(dispatch_get_main_queue()) { () ->
Void in
block()
}
}
}
dispatch_sync_main {
self.tableView.reloadData()
}
Initialize Immutable
Variable Using Closure
• closure と switch 文を使うとかっこよく書ける


let color: UIColor = {
switch value % 2 {
case 0: return UIColor.whiteColor()
case 1: return UIColor.redColor()
default: fatalError()
}
}() // "()" !!
Initialize Immutable
Variable Using Closure
• closure と switch 文を使うとかっこよく書ける


let color: UIColor = {
switch value % 2 {
case 0: return UIColor.whiteColor()
case 1: return UIColor.redColor()
default: fatalError()
}
}() // "()" !!
Changing Behavior with
Using Closure
typealias DrawingHandler = (UIPanGestureRecognizer)->()
class MyView: UIView {
func panGesture(sender: UIPanGestureRecognizer) {
self.drawingHandler(sender)
}
var drawingHandler: DrawingHandler!
let ovalGesture: DrawingHandler = { gesture in
// draw oval
}
let rectangleGesture: DrawingHandler = { gesture in
// draw rectangle
}
}
Changing Behavior with
Using Closure
typealias DrawingHandler = (UIPanGestureRecognizer)->()
class MyView: UIView {
func panGesture(sender: UIPanGestureRecognizer) {
self.drawingHandler(sender)
}
var drawingHandler: DrawingHandler!
let ovalGesture: DrawingHandler = { gesture in
// draw oval
}
let rectangleGesture: DrawingHandler = { gesture in
// draw rectangle
}
}
lazy
When should I use lazy?
• 処理が重くて初期化時に実行するのは不都合
• 大人の理由で init で初期化できないプロパティ
Using lazy var
class MyObject {
lazy var path: String = {
return NSBundle.mainBundle()
.pathForResource("text", ofType: "txt")!
}()
lazy var text: String = {
return try! String(contentsOfFile: self.path)
}()
}
Initializing code per
instance
• 何回呼ばれてもインスタンス毎に一度のみ初期化するコード
class MyView: UIView {
override func layoutSubviews() {
print("MyView: (#function)")
super.layoutSubviews()
setup()
}
private lazy var setup: (()->()) = {
print("MyView: (#function)")
// さまざまな初期化のコード
return {}
}()
}
http://qiita.com/codelynx/items/f0243d631f2448e8
Singleton
Singleton
• 典型的なシングルトン


class Manager {
static let sharedManager = Manager()
private init() {
}
}
• クロージャーを使ったシングルトン
class Manager {
static var sharedManager: Manager = {
return Manager()
}()
private init() {
}
}
http://qiita.com/codelynx/items/a936afe0a45d4cf5abfb
Updating C style 

`for` statement
http://qiita.com/codelynx/items/899c26dd2cbdba7d2b00
for var i = 0 ; i < 100 ; i++
// C-Style for statement
for var i = 0 ; i < 100 ; i++ {
print("(i)")
}
// Swift 3.0 ready
(0 ..< 100).forEach { print("($0)") }
// Swift 3.0 ready
for i in (0 ..< 100) {
print("(i)")
}
for var i = 99 ; i >= 0 ; i--
// C-Style for statement
for var i = 99 ; i >= 0 ; i-- {
print("(i)")
}
// Swift 3.0 ready
(0 ..< 100).reverse().forEach { print("($0)") }
// Swift 3.0 ready
for i in (0 ..< 100).reverse() {
print("(i)")
}
for var i = 0; i < 100 ; i += 2
// C-Style for statement
for var i = 0; i < 100 ; i += 2 {
print("(i)")
}
// Swift 3.0 ready
0.stride(to: 100, by: 2).forEach { print("($0)") }
for var i = 98 ; i >= 0 ; i -=
2
// C-Style for statement
for var i = 98 ; i >= 0 ; i -= 2 {
print("(i)")
}
// Swift 3.0 ready
98.stride(through: 0, by: -2).forEach { print("($0)") }
// Swift 3.0 ready
0.stride(to: 100, by: 2).reverse().forEach { print("($0)") }
// Swift 3.0 ready
for i in 0.stride(to: 100, by: 2).reverse() {
print("(i)")
}
for without increment
• 次の再初期化式の指定がなく、刻みが不定の場合
// C-Style for statement
for var i = 0 ; i < 100 ; {
print("(i)")
if (i * i) % 2 == 0 { i += 1 }
else { i += 2 }
}
// Swift 3.0 ready
var i = 0
while i < 100 {
print("(i)")
if (i * i) % 2 == 0 { i += 1 }
else { i += 2 }
}
Computed Properties
and Property Observer
Custom Property
class MyObject {
private var _name: String = ""
var name: String {
get { return _name }
set { _name = newValue }
}
}
Property Observer
class MyView: UIView {
var name: String = "" {
didSet {
self.setNeedsLayout()
}
}
}
Wrap Up
Wrap up
• 知っていても、0.2秒で思い出せない記法はいろいろあ
る
• Open Source を散策して先人達の記法を参考に
• 気がついた記法があれば、playground などにメモ
• 時々、swift 文法書を眺め直してみよう
Thank You
Kaz Yoshikawa
kaz@digitallynx.com

Weitere ähnliche Inhalte

Was ist angesagt?

Closure, Higher-order function in Swift
Closure, Higher-order function in SwiftClosure, Higher-order function in Swift
Closure, Higher-order function in SwiftSeongGyu Jo
 
ハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使うハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使うbpstudy
 
Modern Application Foundations: Underscore and Twitter Bootstrap
Modern Application Foundations: Underscore and Twitter BootstrapModern Application Foundations: Underscore and Twitter Bootstrap
Modern Application Foundations: Underscore and Twitter BootstrapHoward Lewis Ship
 
Stanfy MadCode Meetup #9: Functional Programming 101 with Swift
Stanfy MadCode Meetup #9: Functional Programming 101 with SwiftStanfy MadCode Meetup #9: Functional Programming 101 with Swift
Stanfy MadCode Meetup #9: Functional Programming 101 with SwiftStanfy
 
Groovy vs Boilerplate and Ceremony Code
Groovy vs Boilerplate and Ceremony CodeGroovy vs Boilerplate and Ceremony Code
Groovy vs Boilerplate and Ceremony Codestasimus
 
From java to kotlin beyond alt+shift+cmd+k - Droidcon italy
From java to kotlin beyond alt+shift+cmd+k - Droidcon italyFrom java to kotlin beyond alt+shift+cmd+k - Droidcon italy
From java to kotlin beyond alt+shift+cmd+k - Droidcon italyFabio Collini
 
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf MilanFrom Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf MilanFabio Collini
 
Play, Slick, play2-authの間で討死
Play, Slick, play2-authの間で討死Play, Slick, play2-authの間で討死
Play, Slick, play2-authの間で討死Kiwamu Okabe
 
Crazy things done on PHP
Crazy things done on PHPCrazy things done on PHP
Crazy things done on PHPTaras Kalapun
 
λ | Lenses
λ | Lensesλ | Lenses
λ | LensesOpen-IT
 
Taking Perl to Eleven with Higher-Order Functions
Taking Perl to Eleven with Higher-Order FunctionsTaking Perl to Eleven with Higher-Order Functions
Taking Perl to Eleven with Higher-Order FunctionsDavid Golden
 
Introduction to c
Introduction to cIntroduction to c
Introduction to cSayed Ahmed
 
Optionals Swift - Swift Paris Junior #3
Optionals Swift - Swift Paris Junior #3 Optionals Swift - Swift Paris Junior #3
Optionals Swift - Swift Paris Junior #3 LouiseFonteneau
 
FunScript 2013 (with speakers notes)
FunScript 2013 (with speakers notes)FunScript 2013 (with speakers notes)
FunScript 2013 (with speakers notes)Zach Bray
 
20180721 code defragment
20180721 code defragment20180721 code defragment
20180721 code defragmentChiwon Song
 
Et si on en finissait avec CRUD ?
Et si on en finissait avec CRUD ?Et si on en finissait avec CRUD ?
Et si on en finissait avec CRUD ?Julien Vinber
 
Slides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersSlides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersGiovanni924
 
Web Security - Hands-on
Web Security - Hands-onWeb Security - Hands-on
Web Security - Hands-onAndrea Valenza
 

Was ist angesagt? (20)

Unit testing UIView
Unit testing UIViewUnit testing UIView
Unit testing UIView
 
Closure, Higher-order function in Swift
Closure, Higher-order function in SwiftClosure, Higher-order function in Swift
Closure, Higher-order function in Swift
 
ハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使うハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使う
 
Scala best practices
Scala best practicesScala best practices
Scala best practices
 
Modern Application Foundations: Underscore and Twitter Bootstrap
Modern Application Foundations: Underscore and Twitter BootstrapModern Application Foundations: Underscore and Twitter Bootstrap
Modern Application Foundations: Underscore and Twitter Bootstrap
 
Stanfy MadCode Meetup #9: Functional Programming 101 with Swift
Stanfy MadCode Meetup #9: Functional Programming 101 with SwiftStanfy MadCode Meetup #9: Functional Programming 101 with Swift
Stanfy MadCode Meetup #9: Functional Programming 101 with Swift
 
Groovy vs Boilerplate and Ceremony Code
Groovy vs Boilerplate and Ceremony CodeGroovy vs Boilerplate and Ceremony Code
Groovy vs Boilerplate and Ceremony Code
 
From java to kotlin beyond alt+shift+cmd+k - Droidcon italy
From java to kotlin beyond alt+shift+cmd+k - Droidcon italyFrom java to kotlin beyond alt+shift+cmd+k - Droidcon italy
From java to kotlin beyond alt+shift+cmd+k - Droidcon italy
 
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf MilanFrom Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
 
Play, Slick, play2-authの間で討死
Play, Slick, play2-authの間で討死Play, Slick, play2-authの間で討死
Play, Slick, play2-authの間で討死
 
Crazy things done on PHP
Crazy things done on PHPCrazy things done on PHP
Crazy things done on PHP
 
λ | Lenses
λ | Lensesλ | Lenses
λ | Lenses
 
Taking Perl to Eleven with Higher-Order Functions
Taking Perl to Eleven with Higher-Order FunctionsTaking Perl to Eleven with Higher-Order Functions
Taking Perl to Eleven with Higher-Order Functions
 
Introduction to c
Introduction to cIntroduction to c
Introduction to c
 
Optionals Swift - Swift Paris Junior #3
Optionals Swift - Swift Paris Junior #3 Optionals Swift - Swift Paris Junior #3
Optionals Swift - Swift Paris Junior #3
 
FunScript 2013 (with speakers notes)
FunScript 2013 (with speakers notes)FunScript 2013 (with speakers notes)
FunScript 2013 (with speakers notes)
 
20180721 code defragment
20180721 code defragment20180721 code defragment
20180721 code defragment
 
Et si on en finissait avec CRUD ?
Et si on en finissait avec CRUD ?Et si on en finissait avec CRUD ?
Et si on en finissait avec CRUD ?
 
Slides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersSlides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammers
 
Web Security - Hands-on
Web Security - Hands-onWeb Security - Hands-on
Web Security - Hands-on
 

Andere mochten auch

Programming Complex Algorithm in Swift
Programming Complex Algorithm in SwiftProgramming Complex Algorithm in Swift
Programming Complex Algorithm in SwiftKaz Yoshikawa
 
Programming Language Swift Overview
Programming Language Swift OverviewProgramming Language Swift Overview
Programming Language Swift OverviewKaz Yoshikawa
 
Extracting text from PDF (iOS)
Extracting text from PDF (iOS)Extracting text from PDF (iOS)
Extracting text from PDF (iOS)Kaz Yoshikawa
 
обл конкур эко_безопасность
обл конкур эко_безопасностьобл конкур эко_безопасность
обл конкур эко_безопасностьмарина маслова
 
патриотическое воспитание в мбоу сош №1
патриотическое воспитание в мбоу сош №1патриотическое воспитание в мбоу сош №1
патриотическое воспитание в мбоу сош №1марина маслова
 
Zagadki jesienne
Zagadki jesienneZagadki jesienne
Zagadki jesiennegosiak60
 
Game Design Workshop @ Naresuan University
Game Design Workshop @ Naresuan UniversityGame Design Workshop @ Naresuan University
Game Design Workshop @ Naresuan UniversityCarolina Islas Sedano
 
Projectpresentatie Onvoltooid Verleden Tijd
Projectpresentatie Onvoltooid Verleden TijdProjectpresentatie Onvoltooid Verleden Tijd
Projectpresentatie Onvoltooid Verleden Tijdtapispleinvzw
 
activity in fifth grade
activity in fifth gradeactivity in fifth grade
activity in fifth gradeangela iaia
 
Central sensitization as normal response to injury
Central sensitization as normal response to injuryCentral sensitization as normal response to injury
Central sensitization as normal response to injuryArturo Such Sanz
 
Commission report (12.3.2013)
Commission report (12.3.2013)Commission report (12.3.2013)
Commission report (12.3.2013)Myint Naing
 

Andere mochten auch (20)

URLSession Reloaded
URLSession ReloadedURLSession Reloaded
URLSession Reloaded
 
Programming Complex Algorithm in Swift
Programming Complex Algorithm in SwiftProgramming Complex Algorithm in Swift
Programming Complex Algorithm in Swift
 
Programming Language Swift Overview
Programming Language Swift OverviewProgramming Language Swift Overview
Programming Language Swift Overview
 
Extracting text from PDF (iOS)
Extracting text from PDF (iOS)Extracting text from PDF (iOS)
Extracting text from PDF (iOS)
 
Newsstand
NewsstandNewsstand
Newsstand
 
iOSで縦書き
iOSで縦書きiOSで縦書き
iOSで縦書き
 
Lander Eventos
Lander EventosLander Eventos
Lander Eventos
 
Sae2
Sae2Sae2
Sae2
 
обл конкур эко_безопасность
обл конкур эко_безопасностьобл конкур эко_безопасность
обл конкур эко_безопасность
 
патриотическое воспитание в мбоу сош №1
патриотическое воспитание в мбоу сош №1патриотическое воспитание в мбоу сош №1
патриотическое воспитание в мбоу сош №1
 
базы данных викторина
базы данных викторинабазы данных викторина
базы данных викторина
 
Ec if you plus minus
Ec if you plus minusEc if you plus minus
Ec if you plus minus
 
Zagadki jesienne
Zagadki jesienneZagadki jesienne
Zagadki jesienne
 
Game Design Workshop @ Naresuan University
Game Design Workshop @ Naresuan UniversityGame Design Workshop @ Naresuan University
Game Design Workshop @ Naresuan University
 
Projectpresentatie Onvoltooid Verleden Tijd
Projectpresentatie Onvoltooid Verleden TijdProjectpresentatie Onvoltooid Verleden Tijd
Projectpresentatie Onvoltooid Verleden Tijd
 
activity in fifth grade
activity in fifth gradeactivity in fifth grade
activity in fifth grade
 
Practical reliability
Practical reliabilityPractical reliability
Practical reliability
 
Central sensitization as normal response to injury
Central sensitization as normal response to injuryCentral sensitization as normal response to injury
Central sensitization as normal response to injury
 
Commission report (12.3.2013)
Commission report (12.3.2013)Commission report (12.3.2013)
Commission report (12.3.2013)
 
Multimedia
MultimediaMultimedia
Multimedia
 

Ähnlich wie Idioms in swift 2016 05c

Hidden Gems in Swift
Hidden Gems in SwiftHidden Gems in Swift
Hidden Gems in SwiftNetguru
 
Funcitonal Swift Conference: The Functional Way
Funcitonal Swift Conference: The Functional WayFuncitonal Swift Conference: The Functional Way
Funcitonal Swift Conference: The Functional WayNatasha Murashev
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsMichael Pirnat
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기진성 오
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme SwiftMovel
 
OSCON Presentation: Developing High Performance Websites and Modern Apps with...
OSCON Presentation: Developing High Performance Websites and Modern Apps with...OSCON Presentation: Developing High Performance Websites and Modern Apps with...
OSCON Presentation: Developing High Performance Websites and Modern Apps with...Doris Chen
 
Introduction to Go
Introduction to GoIntroduction to Go
Introduction to GoJaehue Jang
 
Go 프로그래밍 소개 - 장재휴, DomainDriven커뮤니티
Go 프로그래밍 소개 - 장재휴, DomainDriven커뮤니티Go 프로그래밍 소개 - 장재휴, DomainDriven커뮤니티
Go 프로그래밍 소개 - 장재휴, DomainDriven커뮤니티JaeYeoul Ahn
 
From android/java to swift (3)
From android/java to swift (3)From android/java to swift (3)
From android/java to swift (3)allanh0526
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecLoïc Descotte
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?Tomasz Wrobel
 
Types and Immutability: why you should care
Types and Immutability: why you should careTypes and Immutability: why you should care
Types and Immutability: why you should careJean Carlo Emer
 
Ruby is Awesome
Ruby is AwesomeRuby is Awesome
Ruby is AwesomeAstrails
 
iOS Development using Swift: Enums, ARC, Delegation, Closures, Table View and...
iOS Development using Swift: Enums, ARC, Delegation, Closures, Table View and...iOS Development using Swift: Enums, ARC, Delegation, Closures, Table View and...
iOS Development using Swift: Enums, ARC, Delegation, Closures, Table View and...Ahmed Ali
 

Ähnlich wie Idioms in swift 2016 05c (20)

Hidden Gems in Swift
Hidden Gems in SwiftHidden Gems in Swift
Hidden Gems in Swift
 
Funcitonal Swift Conference: The Functional Way
Funcitonal Swift Conference: The Functional WayFuncitonal Swift Conference: The Functional Way
Funcitonal Swift Conference: The Functional Way
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) Things
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme Swift
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
 
OSCON Presentation: Developing High Performance Websites and Modern Apps with...
OSCON Presentation: Developing High Performance Websites and Modern Apps with...OSCON Presentation: Developing High Performance Websites and Modern Apps with...
OSCON Presentation: Developing High Performance Websites and Modern Apps with...
 
Introduction to Go
Introduction to GoIntroduction to Go
Introduction to Go
 
Go 프로그래밍 소개 - 장재휴, DomainDriven커뮤니티
Go 프로그래밍 소개 - 장재휴, DomainDriven커뮤니티Go 프로그래밍 소개 - 장재휴, DomainDriven커뮤니티
Go 프로그래밍 소개 - 장재휴, DomainDriven커뮤니티
 
Scala 2 + 2 > 4
Scala 2 + 2 > 4Scala 2 + 2 > 4
Scala 2 + 2 > 4
 
From android/java to swift (3)
From android/java to swift (3)From android/java to swift (3)
From android/java to swift (3)
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
Why Kotlin is your next language?
Why Kotlin is your next language? Why Kotlin is your next language?
Why Kotlin is your next language?
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 
Types and Immutability: why you should care
Types and Immutability: why you should careTypes and Immutability: why you should care
Types and Immutability: why you should care
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Ruby is Awesome
Ruby is AwesomeRuby is Awesome
Ruby is Awesome
 
ddd+scala
ddd+scaladdd+scala
ddd+scala
 
iOS Development using Swift: Enums, ARC, Delegation, Closures, Table View and...
iOS Development using Swift: Enums, ARC, Delegation, Closures, Table View and...iOS Development using Swift: Enums, ARC, Delegation, Closures, Table View and...
iOS Development using Swift: Enums, ARC, Delegation, Closures, Table View and...
 

Kürzlich hochgeladen

Dev.bg DevOps March 2024 Monitoring & Logging
Dev.bg DevOps March 2024 Monitoring & LoggingDev.bg DevOps March 2024 Monitoring & Logging
Dev.bg DevOps March 2024 Monitoring & LoggingMarian Marinov
 
Renewable Energy & Entrepreneurship Workshop_21Feb2024.pdf
Renewable Energy & Entrepreneurship Workshop_21Feb2024.pdfRenewable Energy & Entrepreneurship Workshop_21Feb2024.pdf
Renewable Energy & Entrepreneurship Workshop_21Feb2024.pdfodunowoeminence2019
 
IT3401-WEB ESSENTIALS PRESENTATIONS.pptx
IT3401-WEB ESSENTIALS PRESENTATIONS.pptxIT3401-WEB ESSENTIALS PRESENTATIONS.pptx
IT3401-WEB ESSENTIALS PRESENTATIONS.pptxSAJITHABANUS
 
ChatGPT-and-Generative-AI-Landscape Working of generative ai search
ChatGPT-and-Generative-AI-Landscape Working of generative ai searchChatGPT-and-Generative-AI-Landscape Working of generative ai search
ChatGPT-and-Generative-AI-Landscape Working of generative ai searchrohitcse52
 
Phase noise transfer functions.pptx
Phase noise transfer      functions.pptxPhase noise transfer      functions.pptx
Phase noise transfer functions.pptxSaiGouthamSunkara
 
Quasi-Stochastic Approximation: Algorithm Design Principles with Applications...
Quasi-Stochastic Approximation: Algorithm Design Principles with Applications...Quasi-Stochastic Approximation: Algorithm Design Principles with Applications...
Quasi-Stochastic Approximation: Algorithm Design Principles with Applications...Sean Meyn
 
Lecture 1: Basics of trigonometry (surveying)
Lecture 1: Basics of trigonometry (surveying)Lecture 1: Basics of trigonometry (surveying)
Lecture 1: Basics of trigonometry (surveying)Bahzad5
 
Best-NO1 Best Rohani Amil In Lahore Kala Ilam In Lahore Kala Jadu Amil In Lah...
Best-NO1 Best Rohani Amil In Lahore Kala Ilam In Lahore Kala Jadu Amil In Lah...Best-NO1 Best Rohani Amil In Lahore Kala Ilam In Lahore Kala Jadu Amil In Lah...
Best-NO1 Best Rohani Amil In Lahore Kala Ilam In Lahore Kala Jadu Amil In Lah...Amil baba
 
me3493 manufacturing technology unit 1 Part A
me3493 manufacturing technology unit 1 Part Ame3493 manufacturing technology unit 1 Part A
me3493 manufacturing technology unit 1 Part Akarthi keyan
 
SUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docx
SUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docxSUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docx
SUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docxNaveenVerma126
 
دليل تجارب الاسفلت المختبرية - Asphalt Experiments Guide Laboratory
دليل تجارب الاسفلت المختبرية - Asphalt Experiments Guide Laboratoryدليل تجارب الاسفلت المختبرية - Asphalt Experiments Guide Laboratory
دليل تجارب الاسفلت المختبرية - Asphalt Experiments Guide LaboratoryBahzad5
 
Guardians and Glitches: Navigating the Duality of Gen AI in AppSec
Guardians and Glitches: Navigating the Duality of Gen AI in AppSecGuardians and Glitches: Navigating the Duality of Gen AI in AppSec
Guardians and Glitches: Navigating the Duality of Gen AI in AppSecTrupti Shiralkar, CISSP
 
Graphics Primitives and CG Display Devices
Graphics Primitives and CG Display DevicesGraphics Primitives and CG Display Devices
Graphics Primitives and CG Display DevicesDIPIKA83
 
UNIT4_ESD_wfffffggggggggggggith_ARM.pptx
UNIT4_ESD_wfffffggggggggggggith_ARM.pptxUNIT4_ESD_wfffffggggggggggggith_ARM.pptx
UNIT4_ESD_wfffffggggggggggggith_ARM.pptxrealme6igamerr
 
solar wireless electric vechicle charging system
solar wireless electric vechicle charging systemsolar wireless electric vechicle charging system
solar wireless electric vechicle charging systemgokuldongala
 
GENERAL CONDITIONS FOR CONTRACTS OF CIVIL ENGINEERING WORKS
GENERAL CONDITIONS  FOR  CONTRACTS OF CIVIL ENGINEERING WORKS GENERAL CONDITIONS  FOR  CONTRACTS OF CIVIL ENGINEERING WORKS
GENERAL CONDITIONS FOR CONTRACTS OF CIVIL ENGINEERING WORKS Bahzad5
 

Kürzlich hochgeladen (20)

Dev.bg DevOps March 2024 Monitoring & Logging
Dev.bg DevOps March 2024 Monitoring & LoggingDev.bg DevOps March 2024 Monitoring & Logging
Dev.bg DevOps March 2024 Monitoring & Logging
 
Renewable Energy & Entrepreneurship Workshop_21Feb2024.pdf
Renewable Energy & Entrepreneurship Workshop_21Feb2024.pdfRenewable Energy & Entrepreneurship Workshop_21Feb2024.pdf
Renewable Energy & Entrepreneurship Workshop_21Feb2024.pdf
 
IT3401-WEB ESSENTIALS PRESENTATIONS.pptx
IT3401-WEB ESSENTIALS PRESENTATIONS.pptxIT3401-WEB ESSENTIALS PRESENTATIONS.pptx
IT3401-WEB ESSENTIALS PRESENTATIONS.pptx
 
ChatGPT-and-Generative-AI-Landscape Working of generative ai search
ChatGPT-and-Generative-AI-Landscape Working of generative ai searchChatGPT-and-Generative-AI-Landscape Working of generative ai search
ChatGPT-and-Generative-AI-Landscape Working of generative ai search
 
Présentation IIRB 2024 Marine Cordonnier.pdf
Présentation IIRB 2024 Marine Cordonnier.pdfPrésentation IIRB 2024 Marine Cordonnier.pdf
Présentation IIRB 2024 Marine Cordonnier.pdf
 
計劃趕得上變化
計劃趕得上變化計劃趕得上變化
計劃趕得上變化
 
Phase noise transfer functions.pptx
Phase noise transfer      functions.pptxPhase noise transfer      functions.pptx
Phase noise transfer functions.pptx
 
Quasi-Stochastic Approximation: Algorithm Design Principles with Applications...
Quasi-Stochastic Approximation: Algorithm Design Principles with Applications...Quasi-Stochastic Approximation: Algorithm Design Principles with Applications...
Quasi-Stochastic Approximation: Algorithm Design Principles with Applications...
 
Lecture 1: Basics of trigonometry (surveying)
Lecture 1: Basics of trigonometry (surveying)Lecture 1: Basics of trigonometry (surveying)
Lecture 1: Basics of trigonometry (surveying)
 
Best-NO1 Best Rohani Amil In Lahore Kala Ilam In Lahore Kala Jadu Amil In Lah...
Best-NO1 Best Rohani Amil In Lahore Kala Ilam In Lahore Kala Jadu Amil In Lah...Best-NO1 Best Rohani Amil In Lahore Kala Ilam In Lahore Kala Jadu Amil In Lah...
Best-NO1 Best Rohani Amil In Lahore Kala Ilam In Lahore Kala Jadu Amil In Lah...
 
me3493 manufacturing technology unit 1 Part A
me3493 manufacturing technology unit 1 Part Ame3493 manufacturing technology unit 1 Part A
me3493 manufacturing technology unit 1 Part A
 
SUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docx
SUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docxSUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docx
SUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docx
 
دليل تجارب الاسفلت المختبرية - Asphalt Experiments Guide Laboratory
دليل تجارب الاسفلت المختبرية - Asphalt Experiments Guide Laboratoryدليل تجارب الاسفلت المختبرية - Asphalt Experiments Guide Laboratory
دليل تجارب الاسفلت المختبرية - Asphalt Experiments Guide Laboratory
 
Présentation IIRB 2024 Chloe Dufrane.pdf
Présentation IIRB 2024 Chloe Dufrane.pdfPrésentation IIRB 2024 Chloe Dufrane.pdf
Présentation IIRB 2024 Chloe Dufrane.pdf
 
Guardians and Glitches: Navigating the Duality of Gen AI in AppSec
Guardians and Glitches: Navigating the Duality of Gen AI in AppSecGuardians and Glitches: Navigating the Duality of Gen AI in AppSec
Guardians and Glitches: Navigating the Duality of Gen AI in AppSec
 
Graphics Primitives and CG Display Devices
Graphics Primitives and CG Display DevicesGraphics Primitives and CG Display Devices
Graphics Primitives and CG Display Devices
 
Lecture 2 .pptx
Lecture 2                            .pptxLecture 2                            .pptx
Lecture 2 .pptx
 
UNIT4_ESD_wfffffggggggggggggith_ARM.pptx
UNIT4_ESD_wfffffggggggggggggith_ARM.pptxUNIT4_ESD_wfffffggggggggggggith_ARM.pptx
UNIT4_ESD_wfffffggggggggggggith_ARM.pptx
 
solar wireless electric vechicle charging system
solar wireless electric vechicle charging systemsolar wireless electric vechicle charging system
solar wireless electric vechicle charging system
 
GENERAL CONDITIONS FOR CONTRACTS OF CIVIL ENGINEERING WORKS
GENERAL CONDITIONS  FOR  CONTRACTS OF CIVIL ENGINEERING WORKS GENERAL CONDITIONS  FOR  CONTRACTS OF CIVIL ENGINEERING WORKS
GENERAL CONDITIONS FOR CONTRACTS OF CIVIL ENGINEERING WORKS
 

Idioms in swift 2016 05c

  • 1. Idioms in Swift Kaz Yoshikawa May 2016
  • 3. Kaz Yoshikawa • Electricwoods LLC 代表 / Digital Lynx Systems Inc. 副代表 • e-mail: kaz@digitallynx.com • LinkedIn: https://www.linkedin.com/in/kazyoshikawa • Working History • Adobe Systems (Tokyo) • Lionbridge (Tokyo) • Quark (Tokyo / Denver) • Hummingbird Communications (Mt. View, USA) • Fact International (Vancouver, Canada) • Perle Systems (Toronto, Canada), etc.
  • 8. guard let • 二つの引数が nil でない事を保証する func add(a: Int?, _ b: Int?) -> Int? { guard let a = a, let b = b else { return nil } return a + b }
  • 9. if let • if let を使う func add(a: Int?, _ b: Int?) -> Int? { if let a = a, let b = b { return a + b } return nil }
  • 10. where • guard let で0以上を保証する func add(a: Int?, _ b: Int?) -> Int? { guard let a = a, let b = b where a >= 0 && b >= 0 else { return nil } return a + b } • if let でも0以上を保証する func add(a: Int?, _ b: Int?) -> Int? { if let a = a, let b = b where a >= 0 && b >= 0 { return a + b } return nil }
  • 11. nil-coalescing Operator • nil の場合は 0 として扱う func add(a: Int?, b: Int?) -> Int { return (a ?? 0) + (b ?? 0) }
  • 13. Optional in Switch • 実は optional も switch 文に使える func countryName(identifier: String?) -> String? { switch identifier { case "JP"?: return "Japan" case "GB"?: return "England" case "US"?: return "U.S.A." default: return nil } }
  • 14. Late Initializing
 Immutable Variables • 初期値を後で設定する不定変数 let color: UIColor // "= value" switch value % 3 { case 0: color = UIColor.whiteColor() case 1: color = UIColor.redColor() default: fatalError() } • 初期化しないケースがあると、コンパイルエラー
  • 15. Complex switch cases for thing in things { switch thing { case 0 as Int: print("zero as an Int") case 0 as Double: print("zero as a Double") case let someInt as Int: print("an integer value of (someInt)") case let someDouble as Double where someDouble > 0: print("a positive double value of (someDouble)") case is Double: print("some other double value") case let someString as String: print("a string value of "(someString)"") case let (x, y) as (Double, Double): print("an (x, y) point at (x), (y)") case let movie as Movie: print("Movie:'(movie.name)'") default: print("something else") } }
  • 17. Implicitly Unwrapped Optional with if statement • Implicitly Unwrapped Optional でも if let は 使える let a: Int!
 
 if let a = a { print("(a)") }
  • 18. Implicitly Unwrapped Optional with guard statement • Implicitly Unwrapped Optional でも guard は 使える class MyObject { var value: Int! = nil func some() { guard let value = value else { return } print("(value)") } func other() { guard value != nil else { return } print("(value)") } }
  • 20. Defining Associated Value enum Element { case String(Swift.String) case Boolean(Bool) case Integer(Int) case Float(Swift.Float) case Dictionary([Swift.String: Element]) case Array([Element]) case Null } let integer = Element.Integer(42) let city = Element.String("Tokyo") let cities = Element.Array([city]) let dictionary = Element.Dictionary(["items": array])
  • 21. Extracting Associated Values Using switch Statement • Associated Value を Switch文で取り出す switch element { case .String(let string): print("string: (string)") case .Boolean(let value): print("boolean: (value)") case .Integer(let value): print("ineteger: (value)") case .Float(let value): print("float: (value)") case .Dictionary(let dictionary): print("dictionary: (dictionary)") case .Array(let array): print("array: (array)") case .Null: print("null") }
  • 22. Extracting Associated Values using if Statement • If 文でも取り出せます let element1: Element = … if case .String(let string) = element1 { print("(string)") } • Optional な場合でも取り出せます let element: Element? = … if case .String(let string)? = element1 { print("(string)") }
  • 23. Extracting Associated Values • division -> members -> person -> name let name = Element.String("John") let john = Element.Dictionary(["name": name]) let members = Element.Array([john]) let group = Element.Dictionary(["members": members]) • 一発で取り出せる if case .Dictionary(let group) = group, case .Array(let members)? = division["members"], case .Dictionary(let member)? = members.first, case .String(let name)? = member["name"] { print("(name)") // John }
  • 25. Basic Closure class MyViewController: UIViewController { var state: Bool = false func toggle(animated: Bool) { let closure = { self.view.backgroundColor = self.state ? UIColor.redColor() : UIColor.whiteColor() self.state = !self.state } if animated { UIView.animateWithDuration(0.3) { closure() // <-- Here!! } } else { closure() // <-- Here!! } } }
  • 26. Basic Closure class MyViewController: UIViewController { var state: Bool = false func toggle(animated: Bool) { let closure = { self.view.backgroundColor = self.state ? UIColor.redColor() : UIColor.whiteColor() self.state = !self.state } if animated { UIView.animateWithDuration(0.3) { closure() // <-- Here!! } } else { closure() // <-- Here!! } } }
  • 27. Execute on Main Thread func dispatch_sync_main(block: () -> Void) { if NSThread.isMainThread() { block() } else { dispatch_sync(dispatch_get_main_queue()) { () -> Void in block() } } } dispatch_sync_main { self.tableView.reloadData() }
  • 28. Execute on Main Thread func dispatch_sync_main(block: () -> Void) { if NSThread.isMainThread() { block() } else { dispatch_sync(dispatch_get_main_queue()) { () -> Void in block() } } } dispatch_sync_main { self.tableView.reloadData() }
  • 29. Execute on Main Thread func dispatch_sync_main(block: () -> Void) { if NSThread.isMainThread() { block() } else { dispatch_sync(dispatch_get_main_queue()) { () -> Void in block() } } } dispatch_sync_main { self.tableView.reloadData() }
  • 30. Initialize Immutable Variable Using Closure • closure と switch 文を使うとかっこよく書ける 
 let color: UIColor = { switch value % 2 { case 0: return UIColor.whiteColor() case 1: return UIColor.redColor() default: fatalError() } }() // "()" !!
  • 31. Initialize Immutable Variable Using Closure • closure と switch 文を使うとかっこよく書ける 
 let color: UIColor = { switch value % 2 { case 0: return UIColor.whiteColor() case 1: return UIColor.redColor() default: fatalError() } }() // "()" !!
  • 32. Changing Behavior with Using Closure typealias DrawingHandler = (UIPanGestureRecognizer)->() class MyView: UIView { func panGesture(sender: UIPanGestureRecognizer) { self.drawingHandler(sender) } var drawingHandler: DrawingHandler! let ovalGesture: DrawingHandler = { gesture in // draw oval } let rectangleGesture: DrawingHandler = { gesture in // draw rectangle } }
  • 33. Changing Behavior with Using Closure typealias DrawingHandler = (UIPanGestureRecognizer)->() class MyView: UIView { func panGesture(sender: UIPanGestureRecognizer) { self.drawingHandler(sender) } var drawingHandler: DrawingHandler! let ovalGesture: DrawingHandler = { gesture in // draw oval } let rectangleGesture: DrawingHandler = { gesture in // draw rectangle } }
  • 34. lazy
  • 35. When should I use lazy? • 処理が重くて初期化時に実行するのは不都合 • 大人の理由で init で初期化できないプロパティ
  • 36. Using lazy var class MyObject { lazy var path: String = { return NSBundle.mainBundle() .pathForResource("text", ofType: "txt")! }() lazy var text: String = { return try! String(contentsOfFile: self.path) }() }
  • 37. Initializing code per instance • 何回呼ばれてもインスタンス毎に一度のみ初期化するコード class MyView: UIView { override func layoutSubviews() { print("MyView: (#function)") super.layoutSubviews() setup() } private lazy var setup: (()->()) = { print("MyView: (#function)") // さまざまな初期化のコード return {} }() } http://qiita.com/codelynx/items/f0243d631f2448e8
  • 39. Singleton • 典型的なシングルトン 
 class Manager { static let sharedManager = Manager() private init() { } } • クロージャーを使ったシングルトン class Manager { static var sharedManager: Manager = { return Manager() }() private init() { } } http://qiita.com/codelynx/items/a936afe0a45d4cf5abfb
  • 40. Updating C style 
 `for` statement http://qiita.com/codelynx/items/899c26dd2cbdba7d2b00
  • 41. for var i = 0 ; i < 100 ; i++ // C-Style for statement for var i = 0 ; i < 100 ; i++ { print("(i)") } // Swift 3.0 ready (0 ..< 100).forEach { print("($0)") } // Swift 3.0 ready for i in (0 ..< 100) { print("(i)") }
  • 42. for var i = 99 ; i >= 0 ; i-- // C-Style for statement for var i = 99 ; i >= 0 ; i-- { print("(i)") } // Swift 3.0 ready (0 ..< 100).reverse().forEach { print("($0)") } // Swift 3.0 ready for i in (0 ..< 100).reverse() { print("(i)") }
  • 43. for var i = 0; i < 100 ; i += 2 // C-Style for statement for var i = 0; i < 100 ; i += 2 { print("(i)") } // Swift 3.0 ready 0.stride(to: 100, by: 2).forEach { print("($0)") }
  • 44. for var i = 98 ; i >= 0 ; i -= 2 // C-Style for statement for var i = 98 ; i >= 0 ; i -= 2 { print("(i)") } // Swift 3.0 ready 98.stride(through: 0, by: -2).forEach { print("($0)") } // Swift 3.0 ready 0.stride(to: 100, by: 2).reverse().forEach { print("($0)") } // Swift 3.0 ready for i in 0.stride(to: 100, by: 2).reverse() { print("(i)") }
  • 45. for without increment • 次の再初期化式の指定がなく、刻みが不定の場合 // C-Style for statement for var i = 0 ; i < 100 ; { print("(i)") if (i * i) % 2 == 0 { i += 1 } else { i += 2 } } // Swift 3.0 ready var i = 0 while i < 100 { print("(i)") if (i * i) % 2 == 0 { i += 1 } else { i += 2 } }
  • 47. Custom Property class MyObject { private var _name: String = "" var name: String { get { return _name } set { _name = newValue } } }
  • 48. Property Observer class MyView: UIView { var name: String = "" { didSet { self.setNeedsLayout() } } }
  • 50. Wrap up • 知っていても、0.2秒で思い出せない記法はいろいろあ る • Open Source を散策して先人達の記法を参考に • 気がついた記法があれば、playground などにメモ • 時々、swift 文法書を眺め直してみよう