SlideShare ist ein Scribd-Unternehmen logo
1 von 20
Downloaden Sie, um offline zu lesen
Swift Study #7
#이상한모임 @신촌
–Linus Torvalds
‘Talk is cheap. Show me the code.’
Protocol Syntax
protocol SomeProtocol {
// protocol definition goes here
}
!
struct SomeStructure: FirstProtocol, AnotherProtocol
{
// structure definition goes here
}
!
class SomeClass: SomeSuperclass, FirstProtocol,
AnotherProtocol {
// class definition goes here
}
Property Requirements
protocol FullyNamed {
var fullName: String { get }
}
!
struct Person: FullyNamed {
var fullName: String
}
!
let john = Person(fullName: "John Appleseed")
// john.fullName is "John Appleseed"
Property Requirements
class Starship: FullyNamed {
var prefix: String?
var name: String
init(name: String, prefix: String? = nil) {
self.name = name
self.prefix = prefix
}
var fullName: String {
return (prefix != nil ? prefix! + " " : "") + name
}
}
!
var ncc1701 = Starship(name: "Enterprise", prefix: "USS")
// ncc1701.fullName is "USS Enterprise"
Method Requirements
protocol RandomNumberGenerator {
func random() -> Double
}
!
class LinearCongruentialGenerator:
RandomNumberGenerator {
var lastRandom = 42.0
let m = 139968.0, a = 3877.0, c = 29573.0
func random() -> Double {
lastRandom = ((lastRandom * a + c) % m)
return lastRandom / m
}
}
Method Requirements
protocol Togglable {
mutating func toggle()
}
!
enum OnOffSwitch: Togglable {
case Off, On
mutating func toggle() {
switch self {
case Off:
self = On
case On:
self = Off
}
}
}
Protocols as Types
class Dice {
let sides: Int
let generator: RandomNumberGenerator
init(sides: Int, generator: RandomNumberGenerator) {
self.sides = sides
self.generator = generator
}
func roll() -> Int {
return Int(generator.random() * Double(sides)) + 1
}
}
!
var d6 = Dice(sides: 6, generator:
LinearCongruentialGenerator())
for _ in 1...5 { println("Random dice roll is (d6.roll())")
}
Delegation
protocol TodoDelegate {
func sendCompleted(todo: Todo)
}
!
class Notifications: TodoDelegate {
var message: String?
var sent: Bool = false
init() {}
func sendCompleted(todo: Todo) {
println("Completed: (todo.task)")
}
}
Delegation
class Todo {
var task: String
var completed: Bool = false
var delegate: TodoDelegate?
init(task_name: String) {
task = task_name
}
func complete() {
if completed == false {
completed = true
delegate?.sendCompleted(self)
}
}
}
Delegation
let noti = Notifications()
!
let td = Todo(task_name: "Study Swift")
td.delegate = noti
td.complete()
// prints "Completed: Study Swift”
!
let tr = Todo(task_name: "Write Code")
tr.delegate = noti
tr.complete()
// prints "Completed: Write Code"
DelegateProtocol Example
Adding Protocol Conformance with
an Extension
protocol TextRepresentable {
func asText() -> String
}
!
extension Dice: TextRepresentable {
func asText() -> String {
return "A (sides)-sided dice"
}
}
!
let d12 = Dice(sides: 12, generator:
LinearCongruentialGenerator())
println(d12.asText())
// prints "A 12-sided dice"
Declaring Protocol Adoption with an
Extension
struct Hamster {
var name: String
func asText() -> String {
return "A hamster named (name)"
}
}
!
extension Hamster: TextRepresentable {}
!
let simonTheHamster = Hamster(name: "Simon")
let somethingTextRepresentable: TextRepresentable =
simonTheHamster
println(somethingTextRepresentable.asText())
// prints "A hamster named Simon"
Collections of Protocol Types
let things: [TextRepresentable] = [d12,
simonTheHamster]
!
for thing in things {
println(thing.asText())
}
!
// A 12-sided dice
// A hamster named Simon
Protocol Inheritance
protocol PrettyTextRepresentable: TextRepresentable
{
func asPrettyText() -> String
}
!
extension Hamster: PrettyTextRepresentable {
func asPrettyText() -> String {
return "A pretty hamster named (name)"
}
}
!
println(simonTheHamster.asPrettyText())
// prints "A pretty hamster named Simon"
Protocol Composition
protocol Named { var name: String { get } }
!
protocol Aged { var age: Int { get } }
!
struct Person: Named, Aged {
var name: String
var age: Int
}
!
func wishHappyBirthday(celebrator: protocol<Named, Aged>) {
println("Happy birthday (celebrator.name) - you're 
(celebrator.age)!")
}
!
let birthdayPerson = Person(name: "IU", age: 22)
wishHappyBirthday(birthdayPerson)
// prints "Happy birthday IU - you're 22!"
Checking for Protocol Conformance
@objc protocol HasArea {
var area: Double { get }
}
!
class Circle: HasArea { … }
class Country: HasArea { … }
class Animal { … }
!
let objects: [AnyObject] = [Circle(radius: 2.0),Country(area:
243_610),Animal(legs: 4)]
!
for object in objects {
if object is HasArea {
println(object.area)
} else {
println("No area")
}
}
Checking for Protocol Conformance
for object in objects {
if let objectWithArea = object as? HasArea {
println("Area is (objectWithArea.area)")
} else {
println("Something that doesn't have an area")
}
}
Optional Protocol Requirements
@objc protocol CounterDataSource {
optional func incrementForCount(count: Int) -> Int
optional var fixedIncrement: Int { get }
}
!
@objc class Counter {
var count = 0
var dataSource: CounterDataSource?
func increment() {
if let amount = dataSource?.incrementForCount?(count) {
count += amount
} else if let amount = dataSource?.fixedIncrement? {
count += amount
}
}
}
.references
• Protocols in Swift
• 프로토콜(Protocols)
• 프로토콜과 확장

Weitere ähnliche Inhalte

Was ist angesagt?

it's only abuse if it crashes
it's only abuse if it crashesit's only abuse if it crashes
it's only abuse if it crashesEleanor McHugh
 
Type script in practice
Type script in practiceType script in practice
Type script in practiceBryan Hughes
 
Better Software: introduction to good code
Better Software: introduction to good codeBetter Software: introduction to good code
Better Software: introduction to good codeGiordano Scalzo
 
Ruby is an Acceptable Lisp
Ruby is an Acceptable LispRuby is an Acceptable Lisp
Ruby is an Acceptable LispAstrails
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)Pavlo Baron
 
Node Classifier Fundamentals - PuppetConf 2014
Node Classifier Fundamentals - PuppetConf 2014Node Classifier Fundamentals - PuppetConf 2014
Node Classifier Fundamentals - PuppetConf 2014Puppet
 
Crystal: Fundamentos, objetivos y desafios - Cacic 2019
Crystal: Fundamentos, objetivos y desafios - Cacic 2019Crystal: Fundamentos, objetivos y desafios - Cacic 2019
Crystal: Fundamentos, objetivos y desafios - Cacic 2019Brian Cardiff
 
Quick start bash script
Quick start   bash scriptQuick start   bash script
Quick start bash scriptSimon Su
 
Clojure for Java developers - Stockholm
Clojure for Java developers - StockholmClojure for Java developers - Stockholm
Clojure for Java developers - StockholmJan Kronquist
 
The promise of asynchronous PHP
The promise of asynchronous PHPThe promise of asynchronous PHP
The promise of asynchronous PHPWim Godden
 
drb09
drb09drb09
drb09mseki
 
An Introduction to Scala JS
An Introduction to Scala JSAn Introduction to Scala JS
An Introduction to Scala JSKnoldus Inc.
 
React PHP: the NodeJS challenger
React PHP: the NodeJS challengerReact PHP: the NodeJS challenger
React PHP: the NodeJS challengervanphp
 
Puerto serialarduino
Puerto serialarduinoPuerto serialarduino
Puerto serialarduinozadkiel_123
 
JavaOne 2013 - Clojure for Java Developers
JavaOne 2013 - Clojure for Java DevelopersJavaOne 2013 - Clojure for Java Developers
JavaOne 2013 - Clojure for Java DevelopersJan Kronquist
 
Groovy for Java Developers
Groovy for Java DevelopersGroovy for Java Developers
Groovy for Java DevelopersAndres Almiray
 
お題でGroovyプログラミング: Part A
お題でGroovyプログラミング: Part Aお題でGroovyプログラミング: Part A
お題でGroovyプログラミング: Part AKazuchika Sekiya
 
Making Java Groovy (JavaOne 2013)
Making Java Groovy (JavaOne 2013)Making Java Groovy (JavaOne 2013)
Making Java Groovy (JavaOne 2013)Ken Kousen
 

Was ist angesagt? (20)

it's only abuse if it crashes
it's only abuse if it crashesit's only abuse if it crashes
it's only abuse if it crashes
 
Type script in practice
Type script in practiceType script in practice
Type script in practice
 
Better Software: introduction to good code
Better Software: introduction to good codeBetter Software: introduction to good code
Better Software: introduction to good code
 
Bash Scripting Workshop
Bash Scripting WorkshopBash Scripting Workshop
Bash Scripting Workshop
 
Ruby is an Acceptable Lisp
Ruby is an Acceptable LispRuby is an Acceptable Lisp
Ruby is an Acceptable Lisp
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
Node Classifier Fundamentals - PuppetConf 2014
Node Classifier Fundamentals - PuppetConf 2014Node Classifier Fundamentals - PuppetConf 2014
Node Classifier Fundamentals - PuppetConf 2014
 
Crystal: Fundamentos, objetivos y desafios - Cacic 2019
Crystal: Fundamentos, objetivos y desafios - Cacic 2019Crystal: Fundamentos, objetivos y desafios - Cacic 2019
Crystal: Fundamentos, objetivos y desafios - Cacic 2019
 
Quick start bash script
Quick start   bash scriptQuick start   bash script
Quick start bash script
 
Clojure for Java developers - Stockholm
Clojure for Java developers - StockholmClojure for Java developers - Stockholm
Clojure for Java developers - Stockholm
 
The promise of asynchronous PHP
The promise of asynchronous PHPThe promise of asynchronous PHP
The promise of asynchronous PHP
 
drb09
drb09drb09
drb09
 
An Introduction to Scala JS
An Introduction to Scala JSAn Introduction to Scala JS
An Introduction to Scala JS
 
ClojureScript Introduction
ClojureScript IntroductionClojureScript Introduction
ClojureScript Introduction
 
React PHP: the NodeJS challenger
React PHP: the NodeJS challengerReact PHP: the NodeJS challenger
React PHP: the NodeJS challenger
 
Puerto serialarduino
Puerto serialarduinoPuerto serialarduino
Puerto serialarduino
 
JavaOne 2013 - Clojure for Java Developers
JavaOne 2013 - Clojure for Java DevelopersJavaOne 2013 - Clojure for Java Developers
JavaOne 2013 - Clojure for Java Developers
 
Groovy for Java Developers
Groovy for Java DevelopersGroovy for Java Developers
Groovy for Java Developers
 
お題でGroovyプログラミング: Part A
お題でGroovyプログラミング: Part Aお題でGroovyプログラミング: Part A
お題でGroovyプログラミング: Part A
 
Making Java Groovy (JavaOne 2013)
Making Java Groovy (JavaOne 2013)Making Java Groovy (JavaOne 2013)
Making Java Groovy (JavaOne 2013)
 

Ähnlich wie Swift Study #7

No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlinThijs Suijten
 
Introduction to Swift programming language.
Introduction to Swift programming language.Introduction to Swift programming language.
Introduction to Swift programming language.Icalia Labs
 
AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokusHamletDRC
 
Go ahead, make my day
Go ahead, make my dayGo ahead, make my day
Go ahead, make my dayTor Ivry
 
AST Transformations
AST TransformationsAST Transformations
AST TransformationsHamletDRC
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecLoïc Descotte
 
Beauty and Power of Go
Beauty and Power of GoBeauty and Power of Go
Beauty and Power of GoFrank Müller
 
Meetup di GDG Italia - Leonardo Pirro - Codemotion Rome 2018
Meetup di GDG Italia - Leonardo Pirro -  Codemotion Rome 2018 Meetup di GDG Italia - Leonardo Pirro -  Codemotion Rome 2018
Meetup di GDG Italia - Leonardo Pirro - Codemotion Rome 2018 Codemotion
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlinThijs Suijten
 
Are we ready to Go?
Are we ready to Go?Are we ready to Go?
Are we ready to Go?Adam Dudczak
 
Swift 3 Programming for iOS : Protocol
Swift 3 Programming for iOS : ProtocolSwift 3 Programming for iOS : Protocol
Swift 3 Programming for iOS : ProtocolKwang Woo NAM
 
Dts x dicoding #2 memulai pemrograman kotlin
Dts x dicoding #2 memulai pemrograman kotlinDts x dicoding #2 memulai pemrograman kotlin
Dts x dicoding #2 memulai pemrograman kotlinAhmad Arif Faizin
 
Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)HamletDRC
 
Ast transformations
Ast transformationsAst transformations
Ast transformationsHamletDRC
 
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014hwilming
 
Game unleashedjavascript
Game unleashedjavascriptGame unleashedjavascript
Game unleashedjavascriptReece Carlson
 
What's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritageWhat's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritageDroidConTLV
 

Ähnlich wie Swift Study #7 (20)

No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlin
 
Introduction to Swift programming language.
Introduction to Swift programming language.Introduction to Swift programming language.
Introduction to Swift programming language.
 
AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokus
 
Go ahead, make my day
Go ahead, make my dayGo ahead, make my day
Go ahead, make my day
 
Kotlin
KotlinKotlin
Kotlin
 
AST Transformations
AST TransformationsAST Transformations
AST Transformations
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 
Beauty and Power of Go
Beauty and Power of GoBeauty and Power of Go
Beauty and Power of Go
 
Meetup di GDG Italia - Leonardo Pirro - Codemotion Rome 2018
Meetup di GDG Italia - Leonardo Pirro -  Codemotion Rome 2018 Meetup di GDG Italia - Leonardo Pirro -  Codemotion Rome 2018
Meetup di GDG Italia - Leonardo Pirro - Codemotion Rome 2018
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlin
 
Are we ready to Go?
Are we ready to Go?Are we ready to Go?
Are we ready to Go?
 
Swift 3 Programming for iOS : Protocol
Swift 3 Programming for iOS : ProtocolSwift 3 Programming for iOS : Protocol
Swift 3 Programming for iOS : Protocol
 
Dts x dicoding #2 memulai pemrograman kotlin
Dts x dicoding #2 memulai pemrograman kotlinDts x dicoding #2 memulai pemrograman kotlin
Dts x dicoding #2 memulai pemrograman kotlin
 
Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)
 
Ast transformations
Ast transformationsAst transformations
Ast transformations
 
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
 
Game unleashedjavascript
Game unleashedjavascriptGame unleashedjavascript
Game unleashedjavascript
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
What's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritageWhat's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritage
 
Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015
 

Kürzlich hochgeladen

WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...masabamasaba
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
tonesoftg
tonesoftgtonesoftg
tonesoftglanshi9
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfkalichargn70th171
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...masabamasaba
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...Jittipong Loespradit
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...masabamasaba
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 

Kürzlich hochgeladen (20)

WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 

Swift Study #7

  • 2. –Linus Torvalds ‘Talk is cheap. Show me the code.’
  • 3. Protocol Syntax protocol SomeProtocol { // protocol definition goes here } ! struct SomeStructure: FirstProtocol, AnotherProtocol { // structure definition goes here } ! class SomeClass: SomeSuperclass, FirstProtocol, AnotherProtocol { // class definition goes here }
  • 4. Property Requirements protocol FullyNamed { var fullName: String { get } } ! struct Person: FullyNamed { var fullName: String } ! let john = Person(fullName: "John Appleseed") // john.fullName is "John Appleseed"
  • 5. Property Requirements class Starship: FullyNamed { var prefix: String? var name: String init(name: String, prefix: String? = nil) { self.name = name self.prefix = prefix } var fullName: String { return (prefix != nil ? prefix! + " " : "") + name } } ! var ncc1701 = Starship(name: "Enterprise", prefix: "USS") // ncc1701.fullName is "USS Enterprise"
  • 6. Method Requirements protocol RandomNumberGenerator { func random() -> Double } ! class LinearCongruentialGenerator: RandomNumberGenerator { var lastRandom = 42.0 let m = 139968.0, a = 3877.0, c = 29573.0 func random() -> Double { lastRandom = ((lastRandom * a + c) % m) return lastRandom / m } }
  • 7. Method Requirements protocol Togglable { mutating func toggle() } ! enum OnOffSwitch: Togglable { case Off, On mutating func toggle() { switch self { case Off: self = On case On: self = Off } } }
  • 8. Protocols as Types class Dice { let sides: Int let generator: RandomNumberGenerator init(sides: Int, generator: RandomNumberGenerator) { self.sides = sides self.generator = generator } func roll() -> Int { return Int(generator.random() * Double(sides)) + 1 } } ! var d6 = Dice(sides: 6, generator: LinearCongruentialGenerator()) for _ in 1...5 { println("Random dice roll is (d6.roll())") }
  • 9. Delegation protocol TodoDelegate { func sendCompleted(todo: Todo) } ! class Notifications: TodoDelegate { var message: String? var sent: Bool = false init() {} func sendCompleted(todo: Todo) { println("Completed: (todo.task)") } }
  • 10. Delegation class Todo { var task: String var completed: Bool = false var delegate: TodoDelegate? init(task_name: String) { task = task_name } func complete() { if completed == false { completed = true delegate?.sendCompleted(self) } } }
  • 11. Delegation let noti = Notifications() ! let td = Todo(task_name: "Study Swift") td.delegate = noti td.complete() // prints "Completed: Study Swift” ! let tr = Todo(task_name: "Write Code") tr.delegate = noti tr.complete() // prints "Completed: Write Code" DelegateProtocol Example
  • 12. Adding Protocol Conformance with an Extension protocol TextRepresentable { func asText() -> String } ! extension Dice: TextRepresentable { func asText() -> String { return "A (sides)-sided dice" } } ! let d12 = Dice(sides: 12, generator: LinearCongruentialGenerator()) println(d12.asText()) // prints "A 12-sided dice"
  • 13. Declaring Protocol Adoption with an Extension struct Hamster { var name: String func asText() -> String { return "A hamster named (name)" } } ! extension Hamster: TextRepresentable {} ! let simonTheHamster = Hamster(name: "Simon") let somethingTextRepresentable: TextRepresentable = simonTheHamster println(somethingTextRepresentable.asText()) // prints "A hamster named Simon"
  • 14. Collections of Protocol Types let things: [TextRepresentable] = [d12, simonTheHamster] ! for thing in things { println(thing.asText()) } ! // A 12-sided dice // A hamster named Simon
  • 15. Protocol Inheritance protocol PrettyTextRepresentable: TextRepresentable { func asPrettyText() -> String } ! extension Hamster: PrettyTextRepresentable { func asPrettyText() -> String { return "A pretty hamster named (name)" } } ! println(simonTheHamster.asPrettyText()) // prints "A pretty hamster named Simon"
  • 16. Protocol Composition protocol Named { var name: String { get } } ! protocol Aged { var age: Int { get } } ! struct Person: Named, Aged { var name: String var age: Int } ! func wishHappyBirthday(celebrator: protocol<Named, Aged>) { println("Happy birthday (celebrator.name) - you're (celebrator.age)!") } ! let birthdayPerson = Person(name: "IU", age: 22) wishHappyBirthday(birthdayPerson) // prints "Happy birthday IU - you're 22!"
  • 17. Checking for Protocol Conformance @objc protocol HasArea { var area: Double { get } } ! class Circle: HasArea { … } class Country: HasArea { … } class Animal { … } ! let objects: [AnyObject] = [Circle(radius: 2.0),Country(area: 243_610),Animal(legs: 4)] ! for object in objects { if object is HasArea { println(object.area) } else { println("No area") } }
  • 18. Checking for Protocol Conformance for object in objects { if let objectWithArea = object as? HasArea { println("Area is (objectWithArea.area)") } else { println("Something that doesn't have an area") } }
  • 19. Optional Protocol Requirements @objc protocol CounterDataSource { optional func incrementForCount(count: Int) -> Int optional var fixedIncrement: Int { get } } ! @objc class Counter { var count = 0 var dataSource: CounterDataSource? func increment() { if let amount = dataSource?.incrementForCount?(count) { count += amount } else if let amount = dataSource?.fixedIncrement? { count += amount } } }
  • 20. .references • Protocols in Swift • 프로토콜(Protocols) • 프로토콜과 확장