The Swift Compiler and Standard Library

31
The Swift Compiler and the Standard Library Talk at Bangalore Swift Meetup Oct 4 2014 @HasGeek

description

My talk at the Bangalore Swift Meetup - Oct 4 2014.

Transcript of The Swift Compiler and Standard Library

Page 1: The Swift Compiler and Standard Library

The Swift Compiler and the Standard Library

Talk at Bangalore Swift Meetup Oct 4 2014 @HasGeek

Page 2: The Swift Compiler and Standard Library

I am

Santosh Rajan

santoshrajan.com twitter.com/santoshrajan github.com/santoshrajan

in.linkedin.com/in/santoshrajan

Page 3: The Swift Compiler and Standard Library

Chris Lattner

• Author of LLVM since 2002

• Joined Apple 2005

• Author Of the Swift Language since 2010

Page 4: The Swift Compiler and Standard Library

Low Level Virtual Machine (LLVM)

X86 PowerPC ARM SPARC Other..

LLVM

C C++ Objective C ?

Low Level Language

Machine Code

Page 5: The Swift Compiler and Standard Library

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 …

Page 6: The Swift Compiler and Standard Library

Low Level Virtual Machine (LLVM)

X86 PowerPC ARM SPARC Other..

LLVM

C C++ Objective C Swift

Low Level Language

Machine Code

Page 7: The Swift Compiler and Standard Library

Where is Swift?$ xcrun -f swift /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift

Set an Aliasalias swift=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift

Page 8: The Swift Compiler and Standard Library

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

Page 9: The Swift Compiler and Standard Library

Where is the Swift Compiler?

$ xcrun -f swiftc /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc

Set an Aliasalias swiftc=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc

Page 10: The Swift Compiler and Standard Library

Compile and Run$ swiftc hello.swift -o hello $ ./hello Hello World

Generate LLVM bytecode

$ swiftc -emit-bc hello.swift -o hello.bc

Page 11: The Swift Compiler and Standard Library

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

Page 12: The Swift Compiler and Standard Library

Swift Standard Library

• Types

• Protocols

• Operators

• Global Functions

Page 13: The Swift Compiler and Standard Library

TypesCreate Types Using

• Enums

• Structs

• Classes

Enums and Struct are value types. Classes are reference Types.

Page 14: The Swift Compiler and Standard Library

EnumsUse Enums when the Values of the Type are limited. e.g. Planets.

Enum Bit {

case Zero

case One

func Successor() -> Bit

func predecessor() -> Bit

}

Page 15: The Swift Compiler and Standard Library

StructsAll 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

Page 16: The Swift Compiler and Standard Library

Classes

Classes are reference Types. Use Classes when instances are Objects.

Page 17: The Swift Compiler and Standard Library

All TypesArray

AutoreleasingUnsafeMutablePointer

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

Page 18: The Swift Compiler and Standard Library

ProtocolsProtocols 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 }

}

Page 19: The Swift Compiler and Standard Library

SequenceType Protocol

protocol SequenceType {

func generate() -> GeneratorType

}

Types implementing this protocol can be used in for loops. e.g. String, Array, Dictionary

GeneratorType Protocolprotocol GeneratorType {

mutating func next() -> Element?

}

Page 20: The Swift Compiler and Standard Library

SequenceType Examplevar arr = ["Hello", "how", "are", “you"]

var generator = arr.generate()

while let elem = generator.next() { println(elem) }

Is the same asfor elem in arr { println(elem) }

In fact the swift compiler will will compile the `for loop` into the `while loop` above.

Page 21: The Swift Compiler and Standard Library

All ProtocolsAbsoluteValuable

AnyObject

ArrayLiteralConvertible

BidirectionalIndexType

BitwiseOperationsType

BooleanLiteralConvertible

BooleanType

CVarArgType

CollectionType

Comparable

DebugPrintable

DictionaryLiteralConvertible

Equatable

ExtendedGraphemeClusterLiteralConvertible

ExtensibleCollectionType

FloatLiteralConvertible

FloatingPointType

ForwardIndexType

GeneratorType

Hashable

IntegerArithmeticType

IntegerLiteralConvertible

IntegerType

IntervalType

MirrorType

MutableCollectionType

MutableSliceable

NilLiteralConvertible

OutputStreamType

Printable

RandomAccessIndexType

RangeReplaceableCollectionType

RawOptionSetType

RawRepresentable

Reflectable

SequenceType

SignedIntegerType

SignedNumberType

SinkType

Sliceable

Streamable

Strideable

StringInterpolationConvertible

StringLiteralConvertible

UnicodeCodecType

UnicodeScalarLiteralConvertible

UnsignedIntegerType

_ArrayBufferType

_BidirectionalIndexType

_CocoaStringType

_CollectionType

_Comparable

_ExtensibleCollectionType

_ForwardIndexType

_Incrementable

_IntegerArithmeticType

_IntegerType

_ObjectiveCBridgeable

_RandomAccessIndexType

_RawOptionSetType

_SequenceType

_Sequence_Type

_SignedIntegerType

_SignedNumberType

_Sliceable

_Strideable

_SwiftNSArrayRequiredOverridesType

_SwiftNSArrayType

_SwiftNSCopyingType

_SwiftNSDictionaryRequiredOverridesType

_SwiftNSDictionaryType

_SwiftNSEnumeratorType

_SwiftNSFastEnumerationType

_SwiftNSStringRequiredOverridesType

_SwiftNSStringType

_UnsignedIntegerType

Page 22: The Swift Compiler and Standard Library

Operators!=

!==

%

%=

&

&%

&&

&*

&+

&-

&/

&=

*

*=

+

+=

-

-=

...

..<

/

/=

<

<<

<<=

<=

==

===

>

>=

>>

>>=

??

^

^=

|

|=

||

~=

~>

prefix !

prefix +

prefix ++

prefix -

prefix --

prefix ~

postfix ++

postfix --

Page 23: The Swift Compiler and Standard Library

Global FunctionsComes 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)

Page 24: The Swift Compiler and Standard Library

assertTakes 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

Page 25: The Swift Compiler and Standard Library

containsTakes 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”)

}

Page 26: The Swift Compiler and Standard Library

enumerateReturns 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)”)

}

Page 27: The Swift Compiler and Standard Library

mapfunc 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?

Page 28: The Swift Compiler and Standard Library

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]

Page 29: The Swift Compiler and Standard Library

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

Page 30: The Swift Compiler and Standard Library

All Global Functionsabs

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

withUnsafeMutablePointers

withUnsafePointer

withUnsafePointers

withVaList

Page 31: The Swift Compiler and Standard Library

ReferencesAuto Generated Docs - Swifter

Airspeed Velocity- swift standard library