SlideShare a Scribd company logo
Swift
Denis Lebedev, iOS @ Yandex
Agenda
• Introduction
• Objective-C bridging
• Good-to-know features
• “Where can I Swift?”
Swift
Chris Lattner, Swift creator
Swift
• Multi-paradigm
• Static, inferred typing
• Bridged with Objective-C
• No pointers
–Someone at WWDC Keynote
It’s like “Objective-C without C.”
Denis  Lebedev, Swift
Swift features
• Namespacing*
• Generic classes & functions
• Named/default parameters
• Functions are first class citizens
• Optional types
Optionals
• Used in situations where value may be absent
• Alternative for obj-c nil passing
• works with any type
Optionals
- (NSInteger)indexOfObject:(id)object;
Optionals
func indexOf(object: AnyObject) -> Int?
Optionals
• Can be safely unwrapped (if/else)
• Can be force unwrapped (runtime exception if
value is missing)
Classes, structs,
enumerations
• Classes passed by reference, structs - by value
• Using a struct has no runtime penalty
• All scalars and even Bool are structs
• Enumerations are extremely powerful
Enumerations
enum Tree {
case Empty
case Leaf
case Node
}
Enumerations
enum Tree {
case Empty
case Leaf(Int)
case Node(Tree, Tree)
}
Enumerations
enum Tree<T> {
case Empty
case Leaf(T)
case Node(Tree, Tree)
}
Enumerations
let tree: Tree<Int> = .Node(.Leaf(1), .Leaf(1))
Enumerations
enum Tree<T> {
case Empty
case Leaf(T)
case Node(Tree, Tree)
func depth<T>(t: Tree<T>) -> Int {
return 0
}
}
Enumerations
enum Tree<T> {
case …
func depth() -> Int {
func _depth<T>(t: Tree<T>) -> Int {
return 0
}
return _depth(self)
}
}
Enumerations
enum Tree<T> {
case …
func depth() -> Int {
func _depth<T>(t: Tree<T>) -> Int {
switch t {
case .Empty:
return 0
}
return _depth(self)
}
}
Enumerations
enum Tree<T> {
case …
func depth() -> Int {
func _depth<T>(t: Tree<T>) -> Int {
switch t {
case .Empty:
return 0
case .Leaf(let _):
return 1
}
return _depth(self)
}
}
Enumerations
enum Tree<T> {
case …
func depth() -> Int {
func _depth<T>(t: Tree<T>) -> Int {
switch t {
case .Empty:
return 0
case .Leaf(let _):
return 1
case .Node(let lhs, let rhs):
return max(_depth(lhs), _depth(rhs))
}
}
return _depth(self)
}
}
Enumerations
enum Tree<T> {
case Empty
case Leaf(T)
case Node(Tree, Tree)
func depth() -> Int {
func _depth<T>(t: Tree<T>) -> Int {
switch t {
case .Empty:
return 0
case .Leaf(let _):
return 1
case .Node(let lhs, let rhs):
return max(_depth(lhs), _depth(rhs))
}
}
return _depth(self)
}
}
Collections
• Array, Dictionary, String (contains Char)
• Collections are structs
• Implicitly bridged to Cocoa collection types
Collections
func filter<S : Sequence>(…) -> Bool) ->
FilterSequenceView<S>
func reverse<C : Collection …>(source: C) ->
ReverseView<C>
Some of operations are lazy evaluated
Collections
func filter<S : Sequence>(…) -> Bool) ->
FilterSequenceView<S>
func reverse<C : Collection …>(source: C) ->
ReverseView<C>
Some of operations are lazy evaluated
Built-in immutability
var b = 3
b += 1
let a = 3
a += 1 // error
Dictionary immutability
let d = ["key0": 0]
d["key"] = 3 //error
d.updateValue(1, forKey: "key1") //error
Array immutability
let c = [1, 2, 3]
c[0] = 3 // success
c.append(5) // fail
Array immutability
let c = [1, 2, 3]
c[0] = 3 // success
c.append(5) // fail
It’s a bug:
https://devforums.apple.com/message/971330#971330
Extensions
• extends any named type (struct, enum, class)
• structures code
Extensions
struct Foo {
let value : Int
}
extension Foo : Printable {
var description : String {
get {return "Foo"}
}
}
extension Foo : Equatable {
}
func ==(lhs: Foo, rhs: Foo) -> Bool {
return lhs.value == rhs.value
}
What Swift is missing
• Preprocessor
• Exceptions
• Access control *
• KVO, KVC
• Compiler attributes (platforms, deprecations, etc.)
• performSelector: is unavailable
Objective-C bridging
• Call Obj-c from Swift
• Call Swift from Objc with limitations
• Call CoreFoundation types directly
• C++ is not allowed (should be wrapped in Objc)
• Subclassing Swift classes not allowed in Objc
Objective-C bridging
• NSArray < - > Array
• NSDictionary < - > Dictionary
• NSNumber - > Int, Double, Float
Objective-C bridging
@objc class Foo {
init (bar: String) { /*...*/ }
}
Objective-C bridging
@objc(objc_Foo)
class Foo {
@objc(initWithBar:)
init (bar: String) { /*...*/ }
}
Objective-C bridging
Foo *foo = [[Foo alloc] initWithBar:@"Bar"];
Objective-C bridging
func convertPoint(point: CGPoint, toWindow window: UIWindow!) ->
CGPoint
- (CGPoint)convertPoint:(CGPoint)point toWindow:(UIWindow *)window
Objective-C bridging
• All object types are mapped as implicitly
unwrapped optionals (T!)
• All ‘id’ types are mapped as ‘AnyObject’
Swift internals
• Swift objects are Obj-c objects
• Implicit root class ‘SwiftObject’
• Ivars type encoding is stored separately
• Method’s vtable
• Name mangling
Name mangling
class Foo {
func bar() -> Bool {
return false
}
}
_TFC9test3Foo3barfS0_FT_Sb
Swift keeps function metadata encoded in function symbols
Performance
• 10-100 x slower than C++ (-O0)
• 10 x slower than C++ (-O3)
• 1 x as C++ (-Ofast)*
Performance
• Swift is still in beta
• Unoptimized calls of retain/release in loops
Cross-platform code
#if os(iOS)
typealias View = UView
#else
typealias View = NSView
#endif
class MyControl : View {
}
Pattern matching
let point = (0, 1)
if point.0 >= 0 && point.0 <= 1 &&
point.1 >= 0 && point.1 <= 1 {
println("I")
}
...
Pattern matching
let point = (0, 1)
switch point {
case (0...1, 0...1):
println("I")
…
}
Pattern matching
let point = (0, 1)
switch point {
case (0, 0):
println("Point is at the origin")
case (0...1, 0...1):
println("I")
case (-1...0, 0...1):
println("II")
case (-1...0, -1...0):
println("III")
case(0...1, -1...0):
println("IV")
default:
println(“I don’t know.")
}
Function currying
func add(a: Int)(b: Int) -> Int {
return a + b
}
let foo = add(5)(b: 3) // 8
let add5 = add(5) // (Int) -> Int
let bar = add5(b: 3) // 8
Auto closures
• Wraps function argument in explicit closure
func assert(condition:() -> Bool, message: String) {
#if DEBUG
if !condition() { println(message) }
#endif
}
assert({5 % 2 == 0}, "5 isn't an even number.")
Auto closures
Wraps function argument in explicit closure
func assert(condition: @auto_closure () -> Bool,
message: String) {
#if DEBUG
if !condition() { println(message) }
#endif
}
assert(5 % 2 == 0, "5 isn't an even number.")
Implicit type conversion
struct Box<T> {
let _value : T
init (_ value: T) {
_value = value
}
}
let boxedInt = Box(1) //Box<Int>
Implicit type conversion
func foo(i: Int) {…}
foo(boxedInt)
//error: ’Box<Int>' is not convertible to 'Int'
Implicit type conversion
extension Box {
@conversion func __conversion() -> T {
return value
}
}
foo(boxedInt) //success
Implicit type conversion
• allows any type to be ‘nil’ (which has NilType)
• allows toll-free-bridging with Cocoa types
Reflection
struct Foo {
var str = "Apple"
let int = 13
func foo() { }
}
reflect(Foo()).count // 2
reflect(Foo())[0].0 // "str"
reflect(Foo())[0].1.summary // "Apple
Direct call of C functions
@asmname - allows to provide a Swift interface for C functions
@asmname("my_c_func")
func my_c_func(UInt64, CMutablePointer<UInt64>) -> CInt;
Scripting and REPL
• xcrun swift - launches REPL
• xcrun -i ‘file.swift’ - executes script
Where can I swift?
• BDD Testing framework: Quick
• Reactive programming: RXSwift
• Model mapping: Crust
• Handy JSON processing: SwiftyJSON
Thx!
@delebedev
lebedzeu@yandex-team.ru
Credits
• http://nondot.org/sabre/
• https://devforums.apple.com/thread/227288
• http://andelf.github.io/blog/2014/06/08/swift-implicit-type-cast/
• https://www.youtube.com/watch?v=Ii-02vhsdVk
• http://www.eswick.com/2014/06/inside-swift/
• http://article.gmane.org/gmane.comp.compilers.clang.devel/37217
• http://stackoverflow.com/questions/24101718/swift-performance-sorting-arrays
• http://www.splasmata.com/?p=2798
• https://github.com/rodionovd/SWRoute/wiki/Function-hooking-in-Swift

More Related Content

PDF
Swift Introduction
PDF
Cocoa Design Patterns in Swift
PDF
Swift Programming Language
PDF
Swift 2
PDF
Swift Programming Language
PDF
Programming Language Swift Overview
PDF
The Swift Compiler and Standard Library
PDF
Introduction to Swift programming language.
Swift Introduction
Cocoa Design Patterns in Swift
Swift Programming Language
Swift 2
Swift Programming Language
Programming Language Swift Overview
The Swift Compiler and Standard Library
Introduction to Swift programming language.

What's hot (20)

PDF
A swift introduction to Swift
PPTX
A Few Interesting Things in Apple's Swift Programming Language
PPT
Developing iOS apps with Swift
PPTX
FParsec Hands On - F#unctional Londoners 2014
PPT
Falcon初印象
PPTX
Kotlin
DOCX
Game unleashedjavascript
PDF
Swift - the future of iOS app development
ODP
The promise of asynchronous PHP
PDF
Swift Programming
PDF
Protocols with Associated Types, and How They Got That Way
PDF
Functional Programming Patterns (NDC London 2014)
PDF
Introduction to Swift
PDF
Quick swift tour
PDF
Hacking parse.y (RubyKansai38)
PDF
Working with Cocoa and Objective-C
PPT
Basic Javascript
PPTX
Kotlin as a Better Java
PDF
Zope component architechture
PDF
Fundamental JavaScript [UTC, March 2014]
A swift introduction to Swift
A Few Interesting Things in Apple's Swift Programming Language
Developing iOS apps with Swift
FParsec Hands On - F#unctional Londoners 2014
Falcon初印象
Kotlin
Game unleashedjavascript
Swift - the future of iOS app development
The promise of asynchronous PHP
Swift Programming
Protocols with Associated Types, and How They Got That Way
Functional Programming Patterns (NDC London 2014)
Introduction to Swift
Quick swift tour
Hacking parse.y (RubyKansai38)
Working with Cocoa and Objective-C
Basic Javascript
Kotlin as a Better Java
Zope component architechture
Fundamental JavaScript [UTC, March 2014]
Ad

Viewers also liked (20)

PDF
Преимущества и недостатки языка Swift
PDF
Денис Лебедев, Swift
PPTX
iOS Development using Swift: Enums, ARC, Delegation, Closures, Table View and...
PDF
Modern Objective-C @ Pragma Night
PDF
Интуит. Разработка приложений для iOS. Лекция 9. Нестандартный интерфейс
PPT
Ios - Intorduction to view controller
PDF
Роман Бусыгин "Yandex Map Kit для iOS в примерах"
PPTX
Thinking in swift ppt
PDF
Интуит. Разработка приложений для iOS. Лекция 11. Расширенные возможности уст...
PDF
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 03)
PDF
iOS (7) Workshop
PDF
Архитектура компилятора Swift
PDF
iOS NSAgora #3: Objective-C vs. Swift
PDF
iOS: Table Views
PDF
Writing Swift code with great testability
PDF
Spring MVC to iOS and the REST
PDF
CS193P Lecture 5 View Animation
PDF
Rambler.iOS #6: App delegate - разделяй и властвуй
PPTX
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOS
PDF
Workshop iOS 2: Swift - Structures
Преимущества и недостатки языка Swift
Денис Лебедев, Swift
iOS Development using Swift: Enums, ARC, Delegation, Closures, Table View and...
Modern Objective-C @ Pragma Night
Интуит. Разработка приложений для iOS. Лекция 9. Нестандартный интерфейс
Ios - Intorduction to view controller
Роман Бусыгин "Yandex Map Kit для iOS в примерах"
Thinking in swift ppt
Интуит. Разработка приложений для iOS. Лекция 11. Расширенные возможности уст...
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 03)
iOS (7) Workshop
Архитектура компилятора Swift
iOS NSAgora #3: Objective-C vs. Swift
iOS: Table Views
Writing Swift code with great testability
Spring MVC to iOS and the REST
CS193P Lecture 5 View Animation
Rambler.iOS #6: App delegate - разделяй и властвуй
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOS
Workshop iOS 2: Swift - Structures
Ad

Similar to Denis Lebedev, Swift (20)

PDF
Functional programming in kotlin with Arrow [Sunnytech 2018]
PPTX
Should i Go there
PPTX
Kotlin coroutines and spring framework
PDF
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
PDF
(How) can we benefit from adopting scala?
PPTX
Types by Adform Research
PDF
Intro to Kotlin
PPTX
KotlinForJavaDevelopers-UJUG.pptx
PDF
Introduction to Python for Plone developers
PDF
Swift, functional programming, and the future of Objective-C
PPT
Os Vanrossum
PDF
Power of functions in a typed world
PDF
Effective Scala (JavaDay Riga 2013)
PPTX
Introduction to Kotlin
PDF
Scala for Java Developers
PPTX
Return of c++
PDF
Value Objects, Full Throttle (to be updated for spring TC39 meetings)
PPTX
Scala for curious
PPTX
Introduction to C++
PPTX
Functional programming in kotlin with Arrow [Sunnytech 2018]
Should i Go there
Kotlin coroutines and spring framework
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
(How) can we benefit from adopting scala?
Types by Adform Research
Intro to Kotlin
KotlinForJavaDevelopers-UJUG.pptx
Introduction to Python for Plone developers
Swift, functional programming, and the future of Objective-C
Os Vanrossum
Power of functions in a typed world
Effective Scala (JavaDay Riga 2013)
Introduction to Kotlin
Scala for Java Developers
Return of c++
Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Scala for curious
Introduction to C++

More from Yandex (20)

PDF
Предсказание оттока игроков из World of Tanks
PDF
Как принять/организовать работу по поисковой оптимизации сайта, Сергей Царик,...
PDF
Структурированные данные, Юлия Тихоход, лекция в Школе вебмастеров Яндекса
PDF
Представление сайта в поиске, Сергей Лысенко, лекция в Школе вебмастеров Яндекса
PDF
Плохие методы продвижения сайта, Екатерины Гладких, лекция в Школе вебмастеро...
PDF
Основные принципы ранжирования, Сергей Царик и Антон Роменский, лекция в Школ...
PDF
Основные принципы индексирования сайта, Александр Смирнов, лекция в Школе веб...
PDF
Мобильное приложение: как и зачем, Александр Лукин, лекция в Школе вебмастеро...
PDF
Сайты на мобильных устройствах, Олег Ножичкин, лекция в Школе вебмастеров Янд...
PDF
Качественная аналитика сайта, Юрий Батиевский, лекция в Школе вебмастеров Янд...
PDF
Что можно и что нужно измерять на сайте, Петр Аброськин, лекция в Школе вебма...
PDF
Как правильно поставить ТЗ на создание сайта, Алексей Бородкин, лекция в Школ...
PDF
Как защитить свой сайт, Пётр Волков, лекция в Школе вебмастеров
PDF
Как правильно составить структуру сайта, Дмитрий Сатин, лекция в Школе вебмас...
PDF
Технические особенности создания сайта, Дмитрий Васильева, лекция в Школе веб...
PDF
Конструкторы для отдельных элементов сайта, Елена Першина, лекция в Школе веб...
PDF
Контент для интернет-магазинов, Катерина Ерошина, лекция в Школе вебмастеров ...
PDF
Как написать хороший текст для сайта, Катерина Ерошина, лекция в Школе вебмас...
PDF
Usability и дизайн - как не помешать пользователю, Алексей Иванов, лекция в Ш...
PDF
Cайт. Зачем он и каким должен быть, Алексей Иванов, лекция в Школе вебмастеро...
Предсказание оттока игроков из World of Tanks
Как принять/организовать работу по поисковой оптимизации сайта, Сергей Царик,...
Структурированные данные, Юлия Тихоход, лекция в Школе вебмастеров Яндекса
Представление сайта в поиске, Сергей Лысенко, лекция в Школе вебмастеров Яндекса
Плохие методы продвижения сайта, Екатерины Гладких, лекция в Школе вебмастеро...
Основные принципы ранжирования, Сергей Царик и Антон Роменский, лекция в Школ...
Основные принципы индексирования сайта, Александр Смирнов, лекция в Школе веб...
Мобильное приложение: как и зачем, Александр Лукин, лекция в Школе вебмастеро...
Сайты на мобильных устройствах, Олег Ножичкин, лекция в Школе вебмастеров Янд...
Качественная аналитика сайта, Юрий Батиевский, лекция в Школе вебмастеров Янд...
Что можно и что нужно измерять на сайте, Петр Аброськин, лекция в Школе вебма...
Как правильно поставить ТЗ на создание сайта, Алексей Бородкин, лекция в Школ...
Как защитить свой сайт, Пётр Волков, лекция в Школе вебмастеров
Как правильно составить структуру сайта, Дмитрий Сатин, лекция в Школе вебмас...
Технические особенности создания сайта, Дмитрий Васильева, лекция в Школе веб...
Конструкторы для отдельных элементов сайта, Елена Першина, лекция в Школе веб...
Контент для интернет-магазинов, Катерина Ерошина, лекция в Школе вебмастеров ...
Как написать хороший текст для сайта, Катерина Ерошина, лекция в Школе вебмас...
Usability и дизайн - как не помешать пользователю, Алексей Иванов, лекция в Ш...
Cайт. Зачем он и каким должен быть, Алексей Иванов, лекция в Школе вебмастеро...

Recently uploaded (20)

PPTX
TLE Review Electricity (Electricity).pptx
PPTX
OMC Textile Division Presentation 2021.pptx
PPTX
cloud_computing_Infrastucture_as_cloud_p
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Encapsulation theory and applications.pdf
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PDF
August Patch Tuesday
PPTX
Machine Learning_overview_presentation.pptx
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Machine learning based COVID-19 study performance prediction
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Mushroom cultivation and it's methods.pdf
PDF
Empathic Computing: Creating Shared Understanding
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
TLE Review Electricity (Electricity).pptx
OMC Textile Division Presentation 2021.pptx
cloud_computing_Infrastucture_as_cloud_p
Group 1 Presentation -Planning and Decision Making .pptx
Accuracy of neural networks in brain wave diagnosis of schizophrenia
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Advanced methodologies resolving dimensionality complications for autism neur...
Encapsulation theory and applications.pdf
SOPHOS-XG Firewall Administrator PPT.pptx
August Patch Tuesday
Machine Learning_overview_presentation.pptx
Encapsulation_ Review paper, used for researhc scholars
Machine learning based COVID-19 study performance prediction
Network Security Unit 5.pdf for BCA BBA.
Mushroom cultivation and it's methods.pdf
Empathic Computing: Creating Shared Understanding
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
Building Integrated photovoltaic BIPV_UPV.pdf

Denis Lebedev, Swift