SlideShare a Scribd company logo
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

More Related Content

What's hot

Unit testing UIView
Unit testing UIViewUnit testing UIView
Unit testing UIView
Pierre Felgines
 
Closure, Higher-order function in Swift
Closure, Higher-order function in SwiftClosure, Higher-order function in Swift
Closure, Higher-order function in Swift
SeongGyu Jo
 
ハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使うハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使う
bpstudy
 
Scala best practices
Scala best practicesScala best practices
Scala best practices
Alexander Zaidel
 
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
Howard 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 Swift
Stanfy
 
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 italy
Fabio 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 Milan
Fabio 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
λ | Lenses
Open-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 Functions
David Golden
 
Introduction to c
Introduction to cIntroduction to c
Introduction to c
Sayed 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 defragment
Chiwon 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-on
Andrea Valenza
 

What's hot (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
 

Viewers also liked

URLSession Reloaded
URLSession ReloadedURLSession Reloaded
URLSession Reloaded
Kaz Yoshikawa
 
Programming Complex Algorithm in Swift
Programming Complex Algorithm in SwiftProgramming Complex Algorithm in Swift
Programming Complex Algorithm in Swift
Kaz Yoshikawa
 
Programming Language Swift Overview
Programming Language Swift OverviewProgramming Language Swift Overview
Programming Language Swift Overview
Kaz Yoshikawa
 
Extracting text from PDF (iOS)
Extracting text from PDF (iOS)Extracting text from PDF (iOS)
Extracting text from PDF (iOS)
Kaz Yoshikawa
 
iOSで縦書き
iOSで縦書きiOSで縦書き
iOSで縦書き
Hashimoto Shogo
 
Lander Eventos
Lander EventosLander Eventos
Lander Eventos
Kelvin Campelo
 
обл конкур эко_безопасность
обл конкур эко_безопасностьобл конкур эко_безопасность
обл конкур эко_безопасностьмарина маслова
 
патриотическое воспитание в мбоу сош №1
патриотическое воспитание в мбоу сош №1патриотическое воспитание в мбоу сош №1
патриотическое воспитание в мбоу сош №1
марина маслова
 
базы данных викторина
базы данных викторинабазы данных викторина
базы данных викторина
марина маслова
 
Ec if you plus minus
Ec if you plus minusEc if you plus minus
Ec if you plus minus
Lynne M. Glynn
 
Zagadki jesienne
Zagadki jesienneZagadki jesienne
Zagadki jesienne
gosiak60
 
Game Design Workshop @ Naresuan University
Game Design Workshop @ Naresuan UniversityGame Design Workshop @ Naresuan University
Game Design Workshop @ Naresuan University
Carolina 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 grade
angela 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 injury
Arturo Such Sanz
 
Commission report (12.3.2013)
Commission report (12.3.2013)Commission report (12.3.2013)
Commission report (12.3.2013)Myint Naing
 

Viewers also liked (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
 

Similar to Idioms in swift 2016 05c

Hidden Gems in Swift
Hidden Gems in SwiftHidden Gems in Swift
Hidden Gems in Swift
Netguru
 
Funcitonal Swift Conference: The Functional Way
Funcitonal Swift Conference: The Functional WayFuncitonal Swift Conference: The Functional Way
Funcitonal Swift Conference: The Functional Way
Natasha 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) Things
Michael Pirnat
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기
진성 오
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme Swift
Movel
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
Christian Baranowski
 
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
 
Go 프로그래밍 소개 - 장재휴, DomainDriven커뮤니티
Go 프로그래밍 소개 - 장재휴, DomainDriven커뮤니티Go 프로그래밍 소개 - 장재휴, DomainDriven커뮤니티
Go 프로그래밍 소개 - 장재휴, DomainDriven커뮤니티
JaeYeoul Ahn
 
Introduction to Go
Introduction to GoIntroduction to Go
Introduction to Go
Jaehue Jang
 
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
 
Why Kotlin is your next language?
Why Kotlin is your next language? Why Kotlin is your next language?
Why Kotlin is your next language?
Aliaksei Zhynhiarouski
 
(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 care
Jean Carlo Emer
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
Aleksandar Prokopec
 
Ruby is Awesome
Ruby is AwesomeRuby is Awesome
Ruby is Awesome
Astrails
 
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...
Ahmed Ali
 

Similar to 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...
 
Go 프로그래밍 소개 - 장재휴, DomainDriven커뮤니티
Go 프로그래밍 소개 - 장재휴, DomainDriven커뮤니티Go 프로그래밍 소개 - 장재휴, DomainDriven커뮤니티
Go 프로그래밍 소개 - 장재휴, DomainDriven커뮤니티
 
Introduction to Go
Introduction to GoIntroduction to Go
Introduction to Go
 
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...
 

Recently uploaded

space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
ongomchris
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
Jayaprasanna4
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
Jayaprasanna4
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
Robbie Edward Sayers
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
AafreenAbuthahir2
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
Osamah Alsalih
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Teleport Manpower Consultant
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
manasideore6
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
bakpo1
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
AmarGB2
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
ydteq
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
Pratik Pawar
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
ankuprajapati0525
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
AhmedHussein950959
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
ViniHema
 

Recently uploaded (20)

space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
 

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 文法書を眺め直してみよう