SlideShare a Scribd company logo
1 of 22
Download to read offline
Swift Школа
Сергей Пронин
Empatika
План
• Интро
• Why Swift?
• Как подружить Objective-C и Swift?
Интро
Сергей Пронин

Ведущий разработчик Empatika
Ведущий разработчик App in the Air
Преподаватель НИУ-ВШЭ
@spronin
sergey@pronin.me
Why Swift?
• Multiple return values
• Optionals -> Safety
• Playgrounds
• Extensions
• Powerful enums
• Sweet syntax
var variable: Double = 55
variable = 12
let constant = 42 //implicit Int
let str = "Answer is (constant)"
var ar: [Int] = [1, 2, 3]
var dic: [String: AnyObject] = ["key": "value",
"num": 123]
for n in ar {
if n % 2 == 0 {
println(n)
}
}
for (key, value) in dic {
println("(key) -> (value)")
}
var optional: String? = "Hello?"
if let exists = optional {
println(exists)
}
if optional != nil {
println(optional!)
}
if optional?.hasSuffix("?") {

println("somebody home?")
}
let lang = "swift"
switch (lang) {
case "swift":
println("young")
case let x where x.hasSuffix("#"):
println("wat?")
case "js", "css":
println("web")
default:
println("java, is it you?")
}
//add <break> to exit clause
//add <fallthrough> to fall through
for i in 0..<ar.count { //0...n = [0,n]
println(ar[i])
}
for var i = 0; i < ar.count; i++ {
println(ar[i])
}
do {
fetchMessagesFromServer()
sleep(5)
} while true
while ar.count > 0 {
ar.removeLast()
}
func confession(name: String) -> String {
return "I miss (name)"
}
confession("my mom")
func fl(a: [AnyObject]) ->
(first: AnyObject, last: AnyObject) {
return (a[0], a[a.count-1])
}
var result = fl(ar)
println(result.first)
println(result.1)
func params(numbers: Int…) -> Int {
var sum = 0
for n in numbers {
sum += n
}
return sum
}
params(1, 1, 2, 3, 5, 8)
func isEven(n: Int) -> Bool {
return n % 2 == 0
}
func filter(a: [Int], check: Int -> Bool)
-> [Int] {
var result: [Int] = []
for n in a {
if check(n) {
result.append(n)
}
}
return result
}
filter(0...10, isEven)
filter(0...10, { (item: Int) -> Bool in
return item % 2 == 0
})
filter(0...100, { item in item % 10 == 0 })
filter(0...100, { $0 % 10 == 0 })
filter(0...100) { $0 % 10 == 0 }
class Shape {
var sides = 0
var name: String
init(name: String) {
self.name = name
}
func description() -> String {
return "Sides -> (sides)"
}
}
var shape = Shape(name: "ama shape")
shape.description()
class Triangle: Shape {
var a, b, c: Int
init(name: String, sides a: Int, _ b: Int, _ c: Int) {
self.a = a
self.b = b
self.c = c
super.init(name: name)
self.sides = 3
}
var perimeter: Int {
get {
return a + b + c
}
}
override func description() -> String {
return "Triangle with perimeter -> (perimeter)"
}
}
var tr = Triangle(name: "Tr", sides: 5, 10, 20)
tr.description
extension Shape {
class func plusFunction() -> String {
return "I’m a class function "
}
}
Shape.plusFunction()
struct StructShape {
//all the same code, actually
static func plusFunction() -> String {
return "Passed by value"
}
}
//struct objects are being passed by value
//class objects are being passed by reference
enum Status: Int {
case Undetermined, Success, Failure
}
func sendRequest() -> Status {
//networking magic
return Status.Success
}
var result = sendRequest()
switch result {
case .Success:
println("success")
case .Failure:
println("failure")
case .Undetermined:
println("n/a")
}
result = Status.fromRaw(1)! //Success
result.toRaw() //1
protocol NetworkingDelegate {
func request(request: NSURLRequest,
completedWithResult result: NSData?)
}
class ServerHelper {
var delegate: NetworkingDelegate?
func doRequest(request: NSURLRequest) {
var data = NSData(contentsOfURL: request.URL)
delegate?.request(request, completedWithResult: data)
}
}
class Controller: NetworkingDelegate {
func request(request: NSURLRequest,
completedWithResult result: NSData?) {
println("magic")
}
let helper = ServerHelper()
helper.delegate = Controller()
let url = NSURL(string: "http://empatika.com")
helper.doRequest(NSURLRequest(URL: url)))
Objective-C + Swift
Готовимся
typedef enum {
StatusSuccess, StatusFailure
} Status
typedef NS_ENUM(NSInteger, Status) {
StatusSuccess, StatusFailure
};
+ (id)sharedInstance {
//your singleton magic
}
+ (instancetype)sharedInstance {
//singleton magic
}
- (instancetype)init {
//initial magic
}
• В существующей Objective-C codebase -> 

New File - Cocoa Touch Class -> Swift ->

Configure Header
• В созданный Bridging Header импортируем все,
что Swift должен видеть из Obj-C

#import “MyAFAPIClient.h”
• Чтобы Obj-C видел из Swift импортируем

#import “ProductModuleName-Swift.h”
• Открыть Swift-классы и протоколы через @objc

@objc(Venue)

class Venue {…}
Перегнать модель или
Controller на Swift
Начать новый проект на
Swift с модели или
Controller-а

More Related Content

What's hot

Artificial intelligence
Artificial intelligenceArtificial intelligence
Artificial intelligenceAditya Sharma
 
Print input-presentation
Print input-presentationPrint input-presentation
Print input-presentationMartin McBride
 
pycon jp 2016 ---- CguTranslate
pycon jp 2016 ---- CguTranslatepycon jp 2016 ---- CguTranslate
pycon jp 2016 ---- CguTranslateRenyuan Lyu
 
Program to sort the n names in an alphabetical order
Program to sort the n names in an alphabetical orderProgram to sort the n names in an alphabetical order
Program to sort the n names in an alphabetical orderSamsil Arefin
 
Why The Free Monad isn't Free
Why The Free Monad isn't FreeWhy The Free Monad isn't Free
Why The Free Monad isn't FreeKelley Robinson
 
Concurrent Application Development using Scala
Concurrent Application Development using ScalaConcurrent Application Development using Scala
Concurrent Application Development using ScalaSiarhiej Siemianchuk
 
Pythonic Graphics
Pythonic GraphicsPythonic Graphics
Pythonic GraphicsKirby Urner
 
20181020 advanced higher-order function
20181020 advanced higher-order function20181020 advanced higher-order function
20181020 advanced higher-order functionChiwon Song
 
Crystal: tipos, peculiaridades y desafios
Crystal: tipos, peculiaridades y desafiosCrystal: tipos, peculiaridades y desafios
Crystal: tipos, peculiaridades y desafiosBrian Cardiff
 
Scalaz 8: A Whole New Game
Scalaz 8: A Whole New GameScalaz 8: A Whole New Game
Scalaz 8: A Whole New GameJohn De Goes
 
Blazing Fast, Pure Effects without Monads — LambdaConf 2018
Blazing Fast, Pure Effects without Monads — LambdaConf 2018Blazing Fast, Pure Effects without Monads — LambdaConf 2018
Blazing Fast, Pure Effects without Monads — LambdaConf 2018John De Goes
 
Introduction to F# for the C# developer
Introduction to F# for the C# developerIntroduction to F# for the C# developer
Introduction to F# for the C# developernjpst8
 
TSP algorithm (Computational Thinking) Dropbox
TSP algorithm (Computational Thinking) DropboxTSP algorithm (Computational Thinking) Dropbox
TSP algorithm (Computational Thinking) DropboxSeb Sear
 
A Language Designer’s Workbench. A one-stop shop for implementation and verif...
A Language Designer’s Workbench. A one-stop shop for implementation and verif...A Language Designer’s Workbench. A one-stop shop for implementation and verif...
A Language Designer’s Workbench. A one-stop shop for implementation and verif...Eelco Visser
 
Monads and friends demystified
Monads and friends demystifiedMonads and friends demystified
Monads and friends demystifiedAlessandro Lacava
 
Sorting programs
Sorting programsSorting programs
Sorting programsVarun Garg
 
DAA Lab File C Programs
DAA Lab File C ProgramsDAA Lab File C Programs
DAA Lab File C ProgramsKandarp Tiwari
 

What's hot (20)

Artificial intelligence
Artificial intelligenceArtificial intelligence
Artificial intelligence
 
F# intro
F# introF# intro
F# intro
 
Print input-presentation
Print input-presentationPrint input-presentation
Print input-presentation
 
pycon jp 2016 ---- CguTranslate
pycon jp 2016 ---- CguTranslatepycon jp 2016 ---- CguTranslate
pycon jp 2016 ---- CguTranslate
 
Program to sort the n names in an alphabetical order
Program to sort the n names in an alphabetical orderProgram to sort the n names in an alphabetical order
Program to sort the n names in an alphabetical order
 
Why The Free Monad isn't Free
Why The Free Monad isn't FreeWhy The Free Monad isn't Free
Why The Free Monad isn't Free
 
Concurrent Application Development using Scala
Concurrent Application Development using ScalaConcurrent Application Development using Scala
Concurrent Application Development using Scala
 
Matlab code for secant method
Matlab code for secant methodMatlab code for secant method
Matlab code for secant method
 
Pythonic Graphics
Pythonic GraphicsPythonic Graphics
Pythonic Graphics
 
20181020 advanced higher-order function
20181020 advanced higher-order function20181020 advanced higher-order function
20181020 advanced higher-order function
 
Crystal: tipos, peculiaridades y desafios
Crystal: tipos, peculiaridades y desafiosCrystal: tipos, peculiaridades y desafios
Crystal: tipos, peculiaridades y desafios
 
Scalaz 8: A Whole New Game
Scalaz 8: A Whole New GameScalaz 8: A Whole New Game
Scalaz 8: A Whole New Game
 
Blazing Fast, Pure Effects without Monads — LambdaConf 2018
Blazing Fast, Pure Effects without Monads — LambdaConf 2018Blazing Fast, Pure Effects without Monads — LambdaConf 2018
Blazing Fast, Pure Effects without Monads — LambdaConf 2018
 
Introduction to F# for the C# developer
Introduction to F# for the C# developerIntroduction to F# for the C# developer
Introduction to F# for the C# developer
 
TSP algorithm (Computational Thinking) Dropbox
TSP algorithm (Computational Thinking) DropboxTSP algorithm (Computational Thinking) Dropbox
TSP algorithm (Computational Thinking) Dropbox
 
A Language Designer’s Workbench. A one-stop shop for implementation and verif...
A Language Designer’s Workbench. A one-stop shop for implementation and verif...A Language Designer’s Workbench. A one-stop shop for implementation and verif...
A Language Designer’s Workbench. A one-stop shop for implementation and verif...
 
Monads and friends demystified
Monads and friends demystifiedMonads and friends demystified
Monads and friends demystified
 
Sorting programs
Sorting programsSorting programs
Sorting programs
 
DAA Lab File C Programs
DAA Lab File C ProgramsDAA Lab File C Programs
DAA Lab File C Programs
 
Ray tracing with ZIO-ZLayer
Ray tracing with ZIO-ZLayerRay tracing with ZIO-ZLayer
Ray tracing with ZIO-ZLayer
 

Viewers also liked

Департамент Программной Инженерии
Департамент Программной ИнженерииДепартамент Программной Инженерии
Департамент Программной ИнженерииSergey Pronin
 

Viewers also liked (8)

Squeek school 4
Squeek school 4Squeek school 4
Squeek school 4
 
Squeek School #5
Squeek School #5Squeek School #5
Squeek School #5
 
Swift School #4
Swift School #4Swift School #4
Swift School #4
 
Squeek School #8
Squeek School #8Squeek School #8
Squeek School #8
 
Squeek School #7
Squeek School #7Squeek School #7
Squeek School #7
 
Squeek school #6
Squeek school #6Squeek school #6
Squeek school #6
 
Департамент Программной Инженерии
Департамент Программной ИнженерииДепартамент Программной Инженерии
Департамент Программной Инженерии
 
PTA Ancillaries
PTA AncillariesPTA Ancillaries
PTA Ancillaries
 

Similar to Swift School #1

Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2Kirill Rozov
 
talk at Virginia Bioinformatics Institute, December 5, 2013
talk at Virginia Bioinformatics Institute, December 5, 2013talk at Virginia Bioinformatics Institute, December 5, 2013
talk at Virginia Bioinformatics Institute, December 5, 2013ericupnorth
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to SwiftGiordano Scalzo
 
Scala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereldScala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereldWerner Hofstra
 
Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlinintelliyole
 
Monadologie
MonadologieMonadologie
Monadologieleague
 
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
 
Scala Functional Patterns
Scala Functional PatternsScala Functional Patterns
Scala Functional Patternsleague
 
ITT 2015 - Saul Mora - Object Oriented Function Programming
ITT 2015 - Saul Mora - Object Oriented Function ProgrammingITT 2015 - Saul Mora - Object Oriented Function Programming
ITT 2015 - Saul Mora - Object Oriented Function ProgrammingIstanbul Tech Talks
 
Idioms in swift 2016 05c
Idioms in swift 2016 05cIdioms in swift 2016 05c
Idioms in swift 2016 05cKaz Yoshikawa
 
Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»SpbDotNet Community
 
Python 101 language features and functional programming
Python 101 language features and functional programmingPython 101 language features and functional programming
Python 101 language features and functional programmingLukasz Dynowski
 

Similar to Swift School #1 (20)

Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2
 
talk at Virginia Bioinformatics Institute, December 5, 2013
talk at Virginia Bioinformatics Institute, December 5, 2013talk at Virginia Bioinformatics Institute, December 5, 2013
talk at Virginia Bioinformatics Institute, December 5, 2013
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
 
Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to Swift
 
Scala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereldScala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereld
 
Quick swift tour
Quick swift tourQuick swift tour
Quick swift tour
 
Einführung in TypeScript
Einführung in TypeScriptEinführung in TypeScript
Einführung in TypeScript
 
Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlin
 
ProgrammingwithGOLang
ProgrammingwithGOLangProgrammingwithGOLang
ProgrammingwithGOLang
 
Monadologie
MonadologieMonadologie
Monadologie
 
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...
 
Scala best practices
Scala best practicesScala best practices
Scala best practices
 
Scala Functional Patterns
Scala Functional PatternsScala Functional Patterns
Scala Functional Patterns
 
ITT 2015 - Saul Mora - Object Oriented Function Programming
ITT 2015 - Saul Mora - Object Oriented Function ProgrammingITT 2015 - Saul Mora - Object Oriented Function Programming
ITT 2015 - Saul Mora - Object Oriented Function Programming
 
Idioms in swift 2016 05c
Idioms in swift 2016 05cIdioms in swift 2016 05c
Idioms in swift 2016 05c
 
Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»
 
Scala 2 + 2 > 4
Scala 2 + 2 > 4Scala 2 + 2 > 4
Scala 2 + 2 > 4
 
Scala taxonomy
Scala taxonomyScala taxonomy
Scala taxonomy
 
Python 101 language features and functional programming
Python 101 language features and functional programmingPython 101 language features and functional programming
Python 101 language features and functional programming
 

More from Sergey Pronin

App in the Air Internship 2018
App in the Air Internship 2018App in the Air Internship 2018
App in the Air Internship 2018Sergey Pronin
 
Things you might have missed from CoreData
Things you might have missed from CoreDataThings you might have missed from CoreData
Things you might have missed from CoreDataSergey Pronin
 
Mera Dev Fest - Swift vs. Obj-C
Mera Dev Fest - Swift vs. Obj-CMera Dev Fest - Swift vs. Obj-C
Mera Dev Fest - Swift vs. Obj-CSergey Pronin
 
Empatika Design Hours
Empatika Design HoursEmpatika Design Hours
Empatika Design HoursSergey Pronin
 
Greenfield Feedback Squeek
Greenfield Feedback SqueekGreenfield Feedback Squeek
Greenfield Feedback SqueekSergey Pronin
 

More from Sergey Pronin (8)

App in the Air Internship 2018
App in the Air Internship 2018App in the Air Internship 2018
App in the Air Internship 2018
 
Things you might have missed from CoreData
Things you might have missed from CoreDataThings you might have missed from CoreData
Things you might have missed from CoreData
 
Mera Dev Fest - Swift vs. Obj-C
Mera Dev Fest - Swift vs. Obj-CMera Dev Fest - Swift vs. Obj-C
Mera Dev Fest - Swift vs. Obj-C
 
Swift School #3
Swift School #3Swift School #3
Swift School #3
 
Swift School #2
Swift School #2Swift School #2
Swift School #2
 
Empatika Design Hours
Empatika Design HoursEmpatika Design Hours
Empatika Design Hours
 
Greenfield Feedback Squeek
Greenfield Feedback SqueekGreenfield Feedback Squeek
Greenfield Feedback Squeek
 
Squeek School #3
Squeek School #3Squeek School #3
Squeek School #3
 

Recently uploaded

Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 

Recently uploaded (20)

Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 

Swift School #1

  • 2. План • Интро • Why Swift? • Как подружить Objective-C и Swift?
  • 3. Интро Сергей Пронин
 Ведущий разработчик Empatika Ведущий разработчик App in the Air Преподаватель НИУ-ВШЭ @spronin sergey@pronin.me
  • 4. Why Swift? • Multiple return values • Optionals -> Safety • Playgrounds • Extensions • Powerful enums • Sweet syntax
  • 5. var variable: Double = 55 variable = 12 let constant = 42 //implicit Int let str = "Answer is (constant)" var ar: [Int] = [1, 2, 3] var dic: [String: AnyObject] = ["key": "value", "num": 123] for n in ar { if n % 2 == 0 { println(n) } } for (key, value) in dic { println("(key) -> (value)") }
  • 6. var optional: String? = "Hello?" if let exists = optional { println(exists) } if optional != nil { println(optional!) } if optional?.hasSuffix("?") {
 println("somebody home?") }
  • 7. let lang = "swift" switch (lang) { case "swift": println("young") case let x where x.hasSuffix("#"): println("wat?") case "js", "css": println("web") default: println("java, is it you?") } //add <break> to exit clause //add <fallthrough> to fall through
  • 8. for i in 0..<ar.count { //0...n = [0,n] println(ar[i]) } for var i = 0; i < ar.count; i++ { println(ar[i]) } do { fetchMessagesFromServer() sleep(5) } while true while ar.count > 0 { ar.removeLast() }
  • 9. func confession(name: String) -> String { return "I miss (name)" } confession("my mom") func fl(a: [AnyObject]) -> (first: AnyObject, last: AnyObject) { return (a[0], a[a.count-1]) } var result = fl(ar) println(result.first) println(result.1)
  • 10. func params(numbers: Int…) -> Int { var sum = 0 for n in numbers { sum += n } return sum } params(1, 1, 2, 3, 5, 8)
  • 11. func isEven(n: Int) -> Bool { return n % 2 == 0 } func filter(a: [Int], check: Int -> Bool) -> [Int] { var result: [Int] = [] for n in a { if check(n) { result.append(n) } } return result } filter(0...10, isEven)
  • 12. filter(0...10, { (item: Int) -> Bool in return item % 2 == 0 }) filter(0...100, { item in item % 10 == 0 }) filter(0...100, { $0 % 10 == 0 }) filter(0...100) { $0 % 10 == 0 }
  • 13. class Shape { var sides = 0 var name: String init(name: String) { self.name = name } func description() -> String { return "Sides -> (sides)" } } var shape = Shape(name: "ama shape") shape.description()
  • 14. class Triangle: Shape { var a, b, c: Int init(name: String, sides a: Int, _ b: Int, _ c: Int) { self.a = a self.b = b self.c = c super.init(name: name) self.sides = 3 } var perimeter: Int { get { return a + b + c } } override func description() -> String { return "Triangle with perimeter -> (perimeter)" } } var tr = Triangle(name: "Tr", sides: 5, 10, 20) tr.description
  • 15. extension Shape { class func plusFunction() -> String { return "I’m a class function " } } Shape.plusFunction() struct StructShape { //all the same code, actually static func plusFunction() -> String { return "Passed by value" } } //struct objects are being passed by value //class objects are being passed by reference
  • 16. enum Status: Int { case Undetermined, Success, Failure } func sendRequest() -> Status { //networking magic return Status.Success } var result = sendRequest() switch result { case .Success: println("success") case .Failure: println("failure") case .Undetermined: println("n/a") } result = Status.fromRaw(1)! //Success result.toRaw() //1
  • 17. protocol NetworkingDelegate { func request(request: NSURLRequest, completedWithResult result: NSData?) } class ServerHelper { var delegate: NetworkingDelegate? func doRequest(request: NSURLRequest) { var data = NSData(contentsOfURL: request.URL) delegate?.request(request, completedWithResult: data) } } class Controller: NetworkingDelegate { func request(request: NSURLRequest, completedWithResult result: NSData?) { println("magic") } let helper = ServerHelper() helper.delegate = Controller() let url = NSURL(string: "http://empatika.com") helper.doRequest(NSURLRequest(URL: url)))
  • 19. Готовимся typedef enum { StatusSuccess, StatusFailure } Status typedef NS_ENUM(NSInteger, Status) { StatusSuccess, StatusFailure };
  • 20. + (id)sharedInstance { //your singleton magic } + (instancetype)sharedInstance { //singleton magic } - (instancetype)init { //initial magic }
  • 21. • В существующей Objective-C codebase -> 
 New File - Cocoa Touch Class -> Swift ->
 Configure Header • В созданный Bridging Header импортируем все, что Swift должен видеть из Obj-C
 #import “MyAFAPIClient.h” • Чтобы Obj-C видел из Swift импортируем
 #import “ProductModuleName-Swift.h” • Открыть Swift-классы и протоколы через @objc
 @objc(Venue)
 class Venue {…}
  • 22. Перегнать модель или Controller на Swift Начать новый проект на Swift с модели или Controller-а