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

The Swift Compiler and Standard Library

  • 1.
    The Swift Compilerand the Standard Library Talk at Bangalore Swift Meetup Oct 4 2014 @HasGeek
  • 2.
    I am SantoshRajan 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 VirtualMachine (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 VirtualMachine (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 theSwift 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 TypesUsing • Enums • Structs • Classes Enums and Struct are value types. Classes are reference Types.
  • 14.
    Enums Use Enumswhen 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 BasicValue 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 arereference 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 aretemplates 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 Typesimplementing 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 vararr = ["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 Comeswith 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 acondition 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 asequence 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 anEnumerateGenerater. 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) funcsquare(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 xin 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 GeneratedDocs - Swifter Airspeed Velocity- swift standard library