SlideShare a Scribd company logo
1 of 31
Download to read offline
The Swift Compiler and 
the Standard Library 
Talk at Bangalore Swift Meetup Oct 4 2014 @HasGeek
I am 
Santosh Rajan 
santoshrajan.com 
twitter.com/santoshrajan 
github.com/santoshrajan 
in.linkedin.com/in/santoshrajan
Chris Lattner 
• Author of LLVM since 2002 
• Joined Apple 2005 
• Author Of the Swift Language since 2010
Low Level Virtual Machine 
(LLVM) 
C C++ Objective C ? 
Low Level Language 
LLVM 
Machine Code 
X86 PowerPC ARM SPARC Other..
Problem 
• C, C++, Objective C too hard for App developers 
Solution 
• Simple Language syntax like JavaScript 
• Static Typing to allow compiler optimisations 
• Higher order functions to enable closures 
• Host of other features …
Low Level Virtual Machine 
(LLVM) 
C C++ Objective C Swift 
Low Level Language 
LLVM 
Machine Code 
X86 PowerPC ARM SPARC Other..
Where is Swift? 
$ xcrun -f swift 
/Applications/Xcode.app/Contents/Developer/Toolchains/ 
XcodeDefault.xctoolchain/usr/bin/swift 
Set an Alias 
alias swift=/Applications/Xcode.app/Contents/Developer/ 
Toolchains/XcodeDefault.xctoolchain/usr/bin/swift
REPL 
$ swift 
Welcome to Swift! Type :help for assistance. 
1> 2 + 2 
$R0: Int = 4 
2> 
Run 
$ echo "println("Hello World")" > hello.swift 
$ swift hello.swift 
Hello World
Where is the Swift Compiler? 
$ xcrun -f swiftc 
/Applications/Xcode.app/Contents/Developer/Toolchains/ 
XcodeDefault.xctoolchain/usr/bin/swiftc 
Set an Alias 
alias swiftc=/Applications/Xcode.app/Contents/ 
Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ 
swiftc
Compile and Run 
$ swiftc hello.swift -o hello 
$ ./hello 
Hello World 
Generate LLVM bytecode 
$ swiftc -emit-bc hello.swift -o hello.bc
Command Line Arguments 
// edit hello.swift to 
! 
dump(Process.arguments) 
$ swift hello.swift foo bar “hello world” 
▿ 4 elements 
— [0]: hello.swift 
— [1]: foo 
— [2]: bar 
— [3]: hello world
Swift Standard Library 
• Types 
• Protocols 
• Operators 
• Global Functions
Types 
Create Types Using 
• Enums 
• Structs 
• Classes 
Enums and Struct are value types. 
Classes are reference Types.
Enums 
Use Enums when the Values of the Type are 
limited. e.g. Planets. 
Enum Bit { 
case Zero 
case One 
func Successor() -> Bit 
func predecessor() -> Bit 
}
Structs 
All Basic Value Types in Swift are defined using 
Structs. e.g. Bool, Int, Float, Double, Array, Dictionary. 
Struct Array<T> { 
var count: Int { get } 
var isEmpty: Bool { get } 
mutating func append(newElement: T) 
mutating func insert(newElement: T, atIndex i: Int) 
} 
Instance Variables 
Instance Methods
Classes 
Classes are reference Types. Use Classes when 
instances are Objects.
All Types 
Array 
AutoreleasingUnsafeMutablePoint 
er 
BidirectionalReverseView 
Bit 
Bool 
CFunctionPointer 
COpaquePointer 
CVaListPointer 
Character 
ClosedInterval 
CollectionOfOne 
ContiguousArray 
Dictionary 
DictionaryGenerator 
DictionaryIndex 
Double 
EmptyCollection 
EmptyGenerator 
EnumerateGenerator 
EnumerateSequence 
FilterCollectionView 
FilterCollectionViewIndex 
FilterGenerator 
FilterSequenceView 
Float 
Float80 
FloatingPointClassification 
GeneratorOf 
GeneratorOfOne 
GeneratorSequence 
HalfOpenInterval 
HeapBuffer 
HeapBufferStorage 
ImplicitlyUnwrappedOptional 
IndexingGenerator 
Int 
Int16 
Int32 
Int64 
Int8 
LazyBidirectionalCollection 
LazyForwardCollection 
LazyRandomAccessCollection 
LazySequence 
MapCollectionView 
MapSequenceGenerator 
MapSequenceView 
MirrorDisposition 
ObjectIdentifier 
OnHeap 
Optional 
PermutationGenerator 
QuickLookObject 
RandomAccessReverseView 
Range 
RangeGenerator 
RawByte 
Repeat 
ReverseBidirectionalIndex 
ReverseRandomAccessIndex 
SequenceOf 
SinkOf 
Slice 
StaticString 
StrideThrough 
StrideThroughGenerator 
StrideTo 
StrideToGenerator 
String 
UInt 
UInt16 
UInt32 
UInt64 
UInt8 
UTF16 
UTF32 
UTF8 
UnicodeDecodingResult 
UnicodeScalar 
Unmanaged 
UnsafeBufferPointer 
UnsafeBufferPointerGenerator 
UnsafeMutableBufferPointer 
UnsafeMutablePointer 
UnsafePointer 
Zip2 
ZipGenerator2
Protocols 
Protocols are templates for Structs and Classes. 
Like interfaces in Java 
Any Type that implements the Printable protocol 
should implement the instance variable `description` 
which is a getter that returns a String. 
! 
protocol Printable { 
var description: String { get } 
}
SequenceType Protocol 
Types implementing this protocol can be used 
in for loops. e.g. String, Array, Dictionary 
protocol SequenceType { 
func generate() -> GeneratorType 
} 
GeneratorType Protocol 
protocol GeneratorType { 
mutating func next() -> Element? 
}
SequenceType Example 
var arr = ["Hello", "how", "are", “you"] 
var generator = arr.generate() 
while let elem = generator.next() { 
println(elem) 
} 
Is the same as 
for elem in arr { 
println(elem) 
} 
In fact the swift compiler will will compile the `for loop` into the 
`while loop` above.
All Protocols 
AbsoluteValuable 
AnyObject 
ArrayLiteralConvertible 
BidirectionalIndexType 
BitwiseOperationsType 
BooleanLiteralConvertible 
BooleanType 
CVarArgType 
CollectionType 
Comparable 
DebugPrintable 
DictionaryLiteralConvertib 
le 
Equatable 
ExtendedGraphemeClusterLit 
eralConvertible 
ExtensibleCollectionType 
FloatLiteralConvertible 
FloatingPointType 
ForwardIndexType 
GeneratorType 
Hashable 
IntegerArithmeticType 
IntegerLiteralConvertible 
IntegerType 
IntervalType 
MirrorType 
MutableCollectionType 
MutableSliceable 
NilLiteralConvertible 
OutputStreamType 
Printable 
RandomAccessIndexType 
RangeReplaceableCollectio 
nType 
RawOptionSetType 
RawRepresentable 
Reflectable 
SequenceType 
SignedIntegerType 
SignedNumberType 
SinkType 
Sliceable 
Streamable 
Strideable 
StringInterpolationConvert 
ible 
StringLiteralConvertible 
UnicodeCodecType 
UnicodeScalarLiteralConver 
tible 
UnsignedIntegerType 
_ArrayBufferType 
_BidirectionalIndexType 
_CocoaStringType 
_CollectionType 
_Comparable 
_ExtensibleCollectionType 
_ForwardIndexType 
_Incrementable 
_IntegerArithmeticType 
_IntegerType 
_ObjectiveCBridgeable 
_RandomAccessIndexType 
_RawOptionSetType 
_SequenceType 
_Sequence_Type 
_SignedIntegerType 
_SignedNumberType 
_Sliceable 
_Strideable 
_SwiftNSArrayRequiredOverri 
desType 
_SwiftNSArrayType 
_SwiftNSCopyingType 
_SwiftNSDictionaryRequiredO 
verridesType 
_SwiftNSDictionaryType 
_SwiftNSEnumeratorType 
_SwiftNSFastEnumerationType 
_SwiftNSStringRequiredOverr 
idesType 
_SwiftNSStringType 
_UnsignedIntegerType
Operators 
!= 
!== 
% 
%= 
& 
&% 
&& 
&* 
&+ 
&- 
&/ 
&= 
* 
*= 
+ 
+= 
- 
-= 
... 
..< 
/ 
/= 
< 
<< 
<<= 
<= 
== 
=== 
> 
>= 
>> 
>>= 
?? 
^ 
^= 
| 
|= 
|| 
~= 
~> 
prefix ! 
prefix + 
prefix ++ 
prefix - 
prefix -- 
prefix ~ 
postfix ++ 
postfix --
Global Functions 
Comes with over 70 Global built in functions. 
Will cover some here. 
Printing to an output stream. Default 
standard out. 
dump(object) 
print(object) 
println(object)
assert 
Takes a condition expression that evaluates to 
true or false, and a message. 
// file assert.swift 
assert(Process.arguments.count > 1, “Argument required”) 
println(“Argument Supplied”) 
! 
! 
$ swift assert.swift // assertion failed: Argument required. 
$ swift assert.swift foo // Argument Supplied
contains 
Takes a sequence and calls the predicate 
function with every element. 
var arr = [“Foo”, “Bar”, “Baz”, “Bez”] 
if contains(arr, {$0 == “Baz”}) { 
println(“Array contains Baz”) 
}
enumerate 
Returns an EnumerateGenerater. The Generator 
returns a tuple containing index and Element. 
var intarray = [1, 2, 3, 4] 
for (index, element) in enumerate(intarray) { 
println(“Item (index): (element)”) 
}
map 
func square(x: Int) -> Int { 
return x * x 
} 
var num: Int? = 10 
println(map(num, square)) // prints Optional(100) 
wut? 
// Haskells fmap for optionals 
func map<T, U>(x: T?, f: (T) -> U) -> U?
map (overloaded) 
func square(x: Int) -> Int { 
return x * x 
} 
let mappedArray = map([1, 2, 3, 4, 5], square) 
// mappedArray is [1, 4, 9, 16, 25] 
// Definitions 
func map<C : CollectionType, T> 
(source: C, transform: (C.Generator.Element) -> T) -> [T] 
func map<S : SequenceType, T> 
(source: S, transform: (S.Generator.Element) -> T) -> [T]
stride 
for x in stride(from: 0, through: 100, by: 10) { 
println(x) 
} 
// 0, 10, 20, 30, 40, 50, 60 , 70, 80, 90, 100 
! 
! 
for x in stride(from: 100, through: 0, by: -10) 
{ 
println(x) 
} 
//100, 90, 80, 70, 60, 50, 40, 30, 20, 10, 0
All Global Functions 
abs 
advance 
alignof 
alignofValue 
assert 
assertionFailure 
contains 
count 
countElements 
debugPrint 
debugPrintln 
distance 
dropFirst 
dropLast 
dump 
enumerate 
equal 
extend 
fatalError 
filter 
find 
first 
getVaList 
indices 
insert 
isEmpty 
join 
last 
lazy 
lexicographicalCompare 
map 
max 
maxElement 
min 
minElement 
numericCast 
overlaps 
partition 
precondition 
preconditionFailure 
prefix 
print 
println 
reduce 
reflect 
removeAll 
removeAtIndex 
removeLast 
removeRange 
reverse 
sizeof 
sizeofValue 
sort 
sorted 
splice 
split 
startsWith 
stride 
strideof 
strideofValue 
suffix 
swap 
toDebugString 
toString 
transcode 
underestimateCount 
unsafeAddressOf 
unsafeBitCast 
unsafeDowncast 
withExtendedLifetime 
withUnsafeMutablePointer 
withUnsafeMutablePointer 
s 
withUnsafePointer 
withUnsafePointers 
withVaList
References 
Auto Generated Docs - Swifter 
Airspeed Velocity- swift standard 
library

More Related Content

What's hot

Advanced Python, Part 1
Advanced Python, Part 1Advanced Python, Part 1
Advanced Python, Part 1Zaar Hai
 
Kotlin as a Better Java
Kotlin as a Better JavaKotlin as a Better Java
Kotlin as a Better JavaGarth Gilmour
 
The Sincerest Form of Flattery
The Sincerest Form of FlatteryThe Sincerest Form of Flattery
The Sincerest Form of FlatteryJosé Paumard
 
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014hwilming
 
Game unleashedjavascript
Game unleashedjavascriptGame unleashedjavascript
Game unleashedjavascriptReece Carlson
 
Python for data science by www.dmdiploma.com
Python for data science by www.dmdiploma.comPython for data science by www.dmdiploma.com
Python for data science by www.dmdiploma.comShwetaAggarwal56
 
Zope component architechture
Zope component architechtureZope component architechture
Zope component architechtureAnatoly Bubenkov
 
Falcon初印象
Falcon初印象Falcon初印象
Falcon初印象勇浩 赖
 
The Sincerest Form of Flattery
The Sincerest Form of FlatteryThe Sincerest Form of Flattery
The Sincerest Form of FlatteryJosé Paumard
 
DISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in JavaDISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in JavaRasan Samarasinghe
 
1 kotlin vs. java: some java issues addressed in kotlin
1  kotlin vs. java: some java issues addressed in kotlin1  kotlin vs. java: some java issues addressed in kotlin
1 kotlin vs. java: some java issues addressed in kotlinSergey Bandysik
 

What's hot (20)

Quick swift tour
Quick swift tourQuick swift tour
Quick swift tour
 
Advanced Python, Part 1
Advanced Python, Part 1Advanced Python, Part 1
Advanced Python, Part 1
 
Python The basics
Python   The basicsPython   The basics
Python The basics
 
Kotlin as a Better Java
Kotlin as a Better JavaKotlin as a Better Java
Kotlin as a Better Java
 
Python
PythonPython
Python
 
The Sincerest Form of Flattery
The Sincerest Form of FlatteryThe Sincerest Form of Flattery
The Sincerest Form of Flattery
 
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
 
DITEC - Programming with Java
DITEC - Programming with JavaDITEC - Programming with Java
DITEC - Programming with Java
 
Programming with Python
Programming with PythonProgramming with Python
Programming with Python
 
02basics
02basics02basics
02basics
 
Game unleashedjavascript
Game unleashedjavascriptGame unleashedjavascript
Game unleashedjavascript
 
Python
PythonPython
Python
 
Python for data science by www.dmdiploma.com
Python for data science by www.dmdiploma.comPython for data science by www.dmdiploma.com
Python for data science by www.dmdiploma.com
 
Zope component architechture
Zope component architechtureZope component architechture
Zope component architechture
 
Falcon初印象
Falcon初印象Falcon初印象
Falcon初印象
 
The Sincerest Form of Flattery
The Sincerest Form of FlatteryThe Sincerest Form of Flattery
The Sincerest Form of Flattery
 
Advanced Python : Decorators
Advanced Python : DecoratorsAdvanced Python : Decorators
Advanced Python : Decorators
 
DISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in JavaDISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in Java
 
Developing iOS apps with Swift
Developing iOS apps with SwiftDeveloping iOS apps with Swift
Developing iOS apps with Swift
 
1 kotlin vs. java: some java issues addressed in kotlin
1  kotlin vs. java: some java issues addressed in kotlin1  kotlin vs. java: some java issues addressed in kotlin
1 kotlin vs. java: some java issues addressed in kotlin
 

Viewers also liked

The Lambda Calculus and The JavaScript
The Lambda Calculus and The JavaScriptThe Lambda Calculus and The JavaScript
The Lambda Calculus and The JavaScriptNorman Richards
 
Swift basic operators-controlflow
Swift basic operators-controlflowSwift basic operators-controlflow
Swift basic operators-controlflowwileychoi
 
Apostila libras-reformulada- completa
Apostila libras-reformulada- completaApostila libras-reformulada- completa
Apostila libras-reformulada- completaAnisia Barros
 
A Product Manager's Job
A Product Manager's JobA Product Manager's Job
A Product Manager's Jobjoshelman
 

Viewers also liked (6)

Algorithms
AlgorithmsAlgorithms
Algorithms
 
The Lambda Calculus and The JavaScript
The Lambda Calculus and The JavaScriptThe Lambda Calculus and The JavaScript
The Lambda Calculus and The JavaScript
 
Swift basic operators-controlflow
Swift basic operators-controlflowSwift basic operators-controlflow
Swift basic operators-controlflow
 
Apostila libras-reformulada- completa
Apostila libras-reformulada- completaApostila libras-reformulada- completa
Apostila libras-reformulada- completa
 
Complexity
ComplexityComplexity
Complexity
 
A Product Manager's Job
A Product Manager's JobA Product Manager's Job
A Product Manager's Job
 

Similar to The Swift Compiler and Standard Library

An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAdam Getchell
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial javaTpoint s
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streamsjessitron
 
Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingRasan Samarasinghe
 
What make Swift Awesome
What make Swift AwesomeWhat make Swift Awesome
What make Swift AwesomeSokna Ly
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)jeffz
 
Kotlin coroutines and spring framework
Kotlin coroutines and spring frameworkKotlin coroutines and spring framework
Kotlin coroutines and spring frameworkSunghyouk Bae
 
An introduction to functional programming with Swift
An introduction to functional programming with SwiftAn introduction to functional programming with Swift
An introduction to functional programming with SwiftFatih Nayebi, Ph.D.
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Chris Adamson
 
Testing for share
Testing for share Testing for share
Testing for share Rajeev Mehta
 
Java Intro
Java IntroJava Intro
Java Introbackdoor
 
devLink - What's New in C# 4?
devLink - What's New in C# 4?devLink - What's New in C# 4?
devLink - What's New in C# 4?Kevin Pilch
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++Manzoor ALam
 
From android/java to swift (3)
From android/java to swift (3)From android/java to swift (3)
From android/java to swift (3)allanh0526
 

Similar to The Swift Compiler and Standard Library (20)

An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
 
Java
JavaJava
Java
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
 
Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programming
 
What make Swift Awesome
What make Swift AwesomeWhat make Swift Awesome
What make Swift Awesome
 
Start with swift
Start with swiftStart with swift
Start with swift
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
 
Kotlin coroutines and spring framework
Kotlin coroutines and spring frameworkKotlin coroutines and spring framework
Kotlin coroutines and spring framework
 
An introduction to functional programming with Swift
An introduction to functional programming with SwiftAn introduction to functional programming with Swift
An introduction to functional programming with Swift
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
 
Testing for share
Testing for share Testing for share
Testing for share
 
The Style of C++ 11
The Style of C++ 11The Style of C++ 11
The Style of C++ 11
 
C
CC
C
 
Java Intro
Java IntroJava Intro
Java Intro
 
devLink - What's New in C# 4?
devLink - What's New in C# 4?devLink - What's New in C# 4?
devLink - What's New in C# 4?
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++
 
Should i Go there
Should i Go thereShould i Go there
Should i Go there
 
From android/java to swift (3)
From android/java to swift (3)From android/java to swift (3)
From android/java to swift (3)
 

Recently uploaded

KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 

Recently uploaded (20)

KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 

The Swift Compiler and Standard Library

  • 1. The Swift Compiler and the Standard Library Talk at Bangalore Swift Meetup Oct 4 2014 @HasGeek
  • 2. I am Santosh Rajan santoshrajan.com twitter.com/santoshrajan github.com/santoshrajan in.linkedin.com/in/santoshrajan
  • 3. Chris Lattner • Author of LLVM since 2002 • Joined Apple 2005 • Author Of the Swift Language since 2010
  • 4. Low Level Virtual Machine (LLVM) C C++ Objective C ? Low Level Language LLVM Machine Code X86 PowerPC ARM SPARC Other..
  • 5. Problem • C, C++, Objective C too hard for App developers Solution • Simple Language syntax like JavaScript • Static Typing to allow compiler optimisations • Higher order functions to enable closures • Host of other features …
  • 6. Low Level Virtual Machine (LLVM) C C++ Objective C Swift Low Level Language LLVM Machine Code X86 PowerPC ARM SPARC Other..
  • 7. Where is Swift? $ xcrun -f swift /Applications/Xcode.app/Contents/Developer/Toolchains/ XcodeDefault.xctoolchain/usr/bin/swift Set an Alias alias swift=/Applications/Xcode.app/Contents/Developer/ Toolchains/XcodeDefault.xctoolchain/usr/bin/swift
  • 8. REPL $ swift Welcome to Swift! Type :help for assistance. 1> 2 + 2 $R0: Int = 4 2> Run $ echo "println("Hello World")" > hello.swift $ swift hello.swift Hello World
  • 9. Where is the Swift Compiler? $ xcrun -f swiftc /Applications/Xcode.app/Contents/Developer/Toolchains/ XcodeDefault.xctoolchain/usr/bin/swiftc Set an Alias alias swiftc=/Applications/Xcode.app/Contents/ Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ swiftc
  • 10. Compile and Run $ swiftc hello.swift -o hello $ ./hello Hello World Generate LLVM bytecode $ swiftc -emit-bc hello.swift -o hello.bc
  • 11. Command Line Arguments // edit hello.swift to ! dump(Process.arguments) $ swift hello.swift foo bar “hello world” ▿ 4 elements — [0]: hello.swift — [1]: foo — [2]: bar — [3]: hello world
  • 12. Swift Standard Library • Types • Protocols • Operators • Global Functions
  • 13. Types Create Types Using • Enums • Structs • Classes Enums and Struct are value types. Classes are reference Types.
  • 14. Enums Use Enums when the Values of the Type are limited. e.g. Planets. Enum Bit { case Zero case One func Successor() -> Bit func predecessor() -> Bit }
  • 15. Structs All Basic Value Types in Swift are defined using Structs. e.g. Bool, Int, Float, Double, Array, Dictionary. Struct Array<T> { var count: Int { get } var isEmpty: Bool { get } mutating func append(newElement: T) mutating func insert(newElement: T, atIndex i: Int) } Instance Variables Instance Methods
  • 16. Classes Classes are reference Types. Use Classes when instances are Objects.
  • 17. All Types Array AutoreleasingUnsafeMutablePoint er BidirectionalReverseView Bit Bool CFunctionPointer COpaquePointer CVaListPointer Character ClosedInterval CollectionOfOne ContiguousArray Dictionary DictionaryGenerator DictionaryIndex Double EmptyCollection EmptyGenerator EnumerateGenerator EnumerateSequence FilterCollectionView FilterCollectionViewIndex FilterGenerator FilterSequenceView Float Float80 FloatingPointClassification GeneratorOf GeneratorOfOne GeneratorSequence HalfOpenInterval HeapBuffer HeapBufferStorage ImplicitlyUnwrappedOptional IndexingGenerator Int Int16 Int32 Int64 Int8 LazyBidirectionalCollection LazyForwardCollection LazyRandomAccessCollection LazySequence MapCollectionView MapSequenceGenerator MapSequenceView MirrorDisposition ObjectIdentifier OnHeap Optional PermutationGenerator QuickLookObject RandomAccessReverseView Range RangeGenerator RawByte Repeat ReverseBidirectionalIndex ReverseRandomAccessIndex SequenceOf SinkOf Slice StaticString StrideThrough StrideThroughGenerator StrideTo StrideToGenerator String UInt UInt16 UInt32 UInt64 UInt8 UTF16 UTF32 UTF8 UnicodeDecodingResult UnicodeScalar Unmanaged UnsafeBufferPointer UnsafeBufferPointerGenerator UnsafeMutableBufferPointer UnsafeMutablePointer UnsafePointer Zip2 ZipGenerator2
  • 18. Protocols Protocols are templates for Structs and Classes. Like interfaces in Java Any Type that implements the Printable protocol should implement the instance variable `description` which is a getter that returns a String. ! protocol Printable { var description: String { get } }
  • 19. SequenceType Protocol Types implementing this protocol can be used in for loops. e.g. String, Array, Dictionary protocol SequenceType { func generate() -> GeneratorType } GeneratorType Protocol protocol GeneratorType { mutating func next() -> Element? }
  • 20. SequenceType Example var arr = ["Hello", "how", "are", “you"] var generator = arr.generate() while let elem = generator.next() { println(elem) } Is the same as for elem in arr { println(elem) } In fact the swift compiler will will compile the `for loop` into the `while loop` above.
  • 21. All Protocols AbsoluteValuable AnyObject ArrayLiteralConvertible BidirectionalIndexType BitwiseOperationsType BooleanLiteralConvertible BooleanType CVarArgType CollectionType Comparable DebugPrintable DictionaryLiteralConvertib le Equatable ExtendedGraphemeClusterLit eralConvertible ExtensibleCollectionType FloatLiteralConvertible FloatingPointType ForwardIndexType GeneratorType Hashable IntegerArithmeticType IntegerLiteralConvertible IntegerType IntervalType MirrorType MutableCollectionType MutableSliceable NilLiteralConvertible OutputStreamType Printable RandomAccessIndexType RangeReplaceableCollectio nType RawOptionSetType RawRepresentable Reflectable SequenceType SignedIntegerType SignedNumberType SinkType Sliceable Streamable Strideable StringInterpolationConvert ible StringLiteralConvertible UnicodeCodecType UnicodeScalarLiteralConver tible UnsignedIntegerType _ArrayBufferType _BidirectionalIndexType _CocoaStringType _CollectionType _Comparable _ExtensibleCollectionType _ForwardIndexType _Incrementable _IntegerArithmeticType _IntegerType _ObjectiveCBridgeable _RandomAccessIndexType _RawOptionSetType _SequenceType _Sequence_Type _SignedIntegerType _SignedNumberType _Sliceable _Strideable _SwiftNSArrayRequiredOverri desType _SwiftNSArrayType _SwiftNSCopyingType _SwiftNSDictionaryRequiredO verridesType _SwiftNSDictionaryType _SwiftNSEnumeratorType _SwiftNSFastEnumerationType _SwiftNSStringRequiredOverr idesType _SwiftNSStringType _UnsignedIntegerType
  • 22. Operators != !== % %= & &% && &* &+ &- &/ &= * *= + += - -= ... ..< / /= < << <<= <= == === > >= >> >>= ?? ^ ^= | |= || ~= ~> prefix ! prefix + prefix ++ prefix - prefix -- prefix ~ postfix ++ postfix --
  • 23. Global Functions Comes with over 70 Global built in functions. Will cover some here. Printing to an output stream. Default standard out. dump(object) print(object) println(object)
  • 24. assert Takes a condition expression that evaluates to true or false, and a message. // file assert.swift assert(Process.arguments.count > 1, “Argument required”) println(“Argument Supplied”) ! ! $ swift assert.swift // assertion failed: Argument required. $ swift assert.swift foo // Argument Supplied
  • 25. contains Takes a sequence and calls the predicate function with every element. var arr = [“Foo”, “Bar”, “Baz”, “Bez”] if contains(arr, {$0 == “Baz”}) { println(“Array contains Baz”) }
  • 26. enumerate Returns an EnumerateGenerater. The Generator returns a tuple containing index and Element. var intarray = [1, 2, 3, 4] for (index, element) in enumerate(intarray) { println(“Item (index): (element)”) }
  • 27. map func square(x: Int) -> Int { return x * x } var num: Int? = 10 println(map(num, square)) // prints Optional(100) wut? // Haskells fmap for optionals func map<T, U>(x: T?, f: (T) -> U) -> U?
  • 28. map (overloaded) func square(x: Int) -> Int { return x * x } let mappedArray = map([1, 2, 3, 4, 5], square) // mappedArray is [1, 4, 9, 16, 25] // Definitions func map<C : CollectionType, T> (source: C, transform: (C.Generator.Element) -> T) -> [T] func map<S : SequenceType, T> (source: S, transform: (S.Generator.Element) -> T) -> [T]
  • 29. stride for x in stride(from: 0, through: 100, by: 10) { println(x) } // 0, 10, 20, 30, 40, 50, 60 , 70, 80, 90, 100 ! ! for x in stride(from: 100, through: 0, by: -10) { println(x) } //100, 90, 80, 70, 60, 50, 40, 30, 20, 10, 0
  • 30. All Global Functions abs advance alignof alignofValue assert assertionFailure contains count countElements debugPrint debugPrintln distance dropFirst dropLast dump enumerate equal extend fatalError filter find first getVaList indices insert isEmpty join last lazy lexicographicalCompare map max maxElement min minElement numericCast overlaps partition precondition preconditionFailure prefix print println reduce reflect removeAll removeAtIndex removeLast removeRange reverse sizeof sizeofValue sort sorted splice split startsWith stride strideof strideofValue suffix swap toDebugString toString transcode underestimateCount unsafeAddressOf unsafeBitCast unsafeDowncast withExtendedLifetime withUnsafeMutablePointer withUnsafeMutablePointer s withUnsafePointer withUnsafePointers withVaList
  • 31. References Auto Generated Docs - Swifter Airspeed Velocity- swift standard library