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

PPTX
[3] 프로세싱과 아두이노
DOC
Seg code
PPTX
Visualization team presentation
PDF
The Death of Final Tagless
PDF
String
PDF
20191116 custom operators in swift
PDF
20180310 functional programming
DOCX
Solutionsfor co2 C Programs for data structures
[3] 프로세싱과 아두이노
Seg code
Visualization team presentation
The Death of Final Tagless
String
20191116 custom operators in swift
20180310 functional programming
Solutionsfor co2 C Programs for data structures

What's hot (20)

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

Viewers also liked (8)

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

Similar to Swift School #1 (20)

PDF
Kotlin Basics - Apalon Kotlin Sprint Part 2
PDF
talk at Virginia Bioinformatics Institute, December 5, 2013
PPT
SDC - Einführung in Scala
PDF
Pooya Khaloo Presentation on IWMC 2015
PDF
A swift introduction to Swift
PDF
Scala: Functioneel programmeren in een object georiënteerde wereld
PDF
Quick swift tour
PDF
Einführung in TypeScript
PDF
Idiomatic Kotlin
PPTX
ProgrammingwithGOLang
PDF
Monadologie
PDF
OSCON Presentation: Developing High Performance Websites and Modern Apps with...
PPTX
Scala best practices
PDF
Scala Functional Patterns
PDF
Idioms in swift 2016 05c
PDF
Дмитрий Верескун «Синтаксический сахар C#»
ODP
Scala 2 + 2 > 4
PDF
Scala taxonomy
PPT
Python 101 language features and functional programming
PDF
Python
Kotlin Basics - Apalon Kotlin Sprint Part 2
talk at Virginia Bioinformatics Institute, December 5, 2013
SDC - Einführung in Scala
Pooya Khaloo Presentation on IWMC 2015
A swift introduction to Swift
Scala: Functioneel programmeren in een object georiënteerde wereld
Quick swift tour
Einführung in TypeScript
Idiomatic Kotlin
ProgrammingwithGOLang
Monadologie
OSCON Presentation: Developing High Performance Websites and Modern Apps with...
Scala best practices
Scala Functional Patterns
Idioms in swift 2016 05c
Дмитрий Верескун «Синтаксический сахар C#»
Scala 2 + 2 > 4
Scala taxonomy
Python 101 language features and functional programming
Python

More from Sergey Pronin (8)

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

Recently uploaded (20)

PPTX
20th Century Theater, Methods, History.pptx
PDF
International_Financial_Reporting_Standa.pdf
PDF
LDMMIA Reiki Yoga Finals Review Spring Summer
PPTX
Virtual and Augmented Reality in Current Scenario
PDF
FOISHS ANNUAL IMPLEMENTATION PLAN 2025.pdf
PPTX
Share_Module_2_Power_conflict_and_negotiation.pptx
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PDF
My India Quiz Book_20210205121199924.pdf
PDF
medical_surgical_nursing_10th_edition_ignatavicius_TEST_BANK_pdf.pdf
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PPTX
B.Sc. DS Unit 2 Software Engineering.pptx
PDF
Environmental Education MCQ BD2EE - Share Source.pdf
PDF
What if we spent less time fighting change, and more time building what’s rig...
PDF
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
PPTX
Introduction to pro and eukaryotes and differences.pptx
PDF
Trump Administration's workforce development strategy
PPTX
TNA_Presentation-1-Final(SAVE)) (1).pptx
PPTX
Unit 4 Computer Architecture Multicore Processor.pptx
PPTX
ELIAS-SEZIURE AND EPilepsy semmioan session.pptx
20th Century Theater, Methods, History.pptx
International_Financial_Reporting_Standa.pdf
LDMMIA Reiki Yoga Finals Review Spring Summer
Virtual and Augmented Reality in Current Scenario
FOISHS ANNUAL IMPLEMENTATION PLAN 2025.pdf
Share_Module_2_Power_conflict_and_negotiation.pptx
Chinmaya Tiranga quiz Grand Finale.pdf
My India Quiz Book_20210205121199924.pdf
medical_surgical_nursing_10th_edition_ignatavicius_TEST_BANK_pdf.pdf
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
B.Sc. DS Unit 2 Software Engineering.pptx
Environmental Education MCQ BD2EE - Share Source.pdf
What if we spent less time fighting change, and more time building what’s rig...
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
Introduction to pro and eukaryotes and differences.pptx
Trump Administration's workforce development strategy
TNA_Presentation-1-Final(SAVE)) (1).pptx
Unit 4 Computer Architecture Multicore Processor.pptx
ELIAS-SEZIURE AND EPilepsy semmioan session.pptx

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