Upload
santosh-rajan
View
1.593
Download
5
Embed Size (px)
DESCRIPTION
My talk at the Bangalore Swift Meetup - Oct 4 2014.
Citation preview
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)
X86 PowerPC ARM SPARC Other..
LLVM
C C++ Objective C ?
Low Level Language
Machine Code
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)
X86 PowerPC ARM SPARC Other..
LLVM
C C++ Objective C Swift
Low Level Language
Machine Code
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
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 Aliasalias 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
TypesCreate Types Using
• Enums
• Structs
• Classes
Enums and Struct are value types. Classes are reference Types.
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
}
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
Classes
Classes are reference Types. Use Classes when instances are Objects.
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
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 }
}
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?
}
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.
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
Operators!=
!==
%
%=
&
&%
&&
&*
&+
&-
&/
&=
*
*=
+
+=
-
-=
...
..<
/
/=
<
<<
<<=
<=
==
===
>
>=
>>
>>=
??
^
^=
|
|=
||
~=
~>
prefix !
prefix +
prefix ++
prefix -
prefix --
prefix ~
postfix ++
postfix --
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)
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
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”)
}
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)”)
}
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?
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 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
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
ReferencesAuto Generated Docs - Swifter
Airspeed Velocity- swift standard library