SlideShare ist ein Scribd-Unternehmen logo
1 von 22
Downloaden Sie, um offline zu lesen
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-а

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Andere mochten auch

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

Andere mochten auch (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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Mehr von 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
 

Mehr von 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
 

Kürzlich hochgeladen

Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 

Kürzlich hochgeladen (20)

Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 

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-а