Share
Embed
CocoaheadsSKG #1 - Introduction to Swift
@tsif makes a great introduction to Swift!
CocoaHeadsSKG
January 26, 2016
Transcript
44 slides
-
About Swift • Safety • Support Cocoa and Cocoa Touch
• Works side by side with Objective-C code • Single implementation file • Error handling, closures, multiple return values, functional programming patterns, generics, fast iteration etc. etc. etc. -
Hello world in Objective-C #import <Foundation/Foundation.h> int main(void) { NSLog(@"Hello,
world!\n"); return 0; } -
Variables and Constants var meetupName : String = “CocoaHeads” var
version : Int = 3 // mutable meetupName = “CocoaHeadsSKG” let meetupCity : String = “Thessaloniki” // immutable meetupCity = “Athens” // error -
Variables and Constants var meetupName = “CocoaHeads” // String var
version = 3 // Int let meetupCity = “Athens” // String let isSummer = true // Bool let π = 3.14 // Double let = " " -
Type aliases Type aliases define an alternative name for an
existing type. You define type aliases with the typealias keyword. -
Type aliases typealias AudioSample = UInt16 var maxAmplitudeFound = AudioSample.min
// maxAmplitudeFound is now 0” -
Type aliases typealias Position = (x: Int, y: Int) //
method “overloading”, illegal in obj-c func takePosition(x: Int, y: Int) { } func takePosition(position: Position) { } takePosition(100, y: 100) takePosition(Position(x: 200, y: 100)) -
String let myString = “I am a String” // inferred
let theirString = myString + “!” let a = 5 let aString = “a is \(a)” // printed as “a is 5” -
Collection Literals var names = [“Eleni”, “Giannis”, “Luke”] var names:
[String] = [“Eleni”, “Giannis”, “Luke”] var names: Array<String> = [“Eleni”, “Giannis”, “Luke”] var numberOfiPhones = [“Eleni”: 2, ”Luke”:0] var d: Dictionary< String, Int> = [“key1”: 1, ”key2”:2] var d: [String: Int] = [“key1”: 1, ”key2”:2] -
Loops while !ending { print(“looping”) } for var i =
0; i < 10; i++ { print(i) } for number in 0...3 { print(“number \(number)” } -
Loops // dictionary literal + tuple for (aKey, aValue) in
[“Eleni”: 2, ”Luke”:0] { print(“aKey \(aKey) aValue \(aValue)” } -
Arrays var aList = [“item0”, “item1”]; aList += “item3” aList
+= [“item4”, “item5”] aList[1] = “listItem1” -
Dictionaries var numberOfiPhones = [“Eleni”: 2, ”Luke”:0] numberOfiPhones[“Luke”] = 1
var vadersPhones = numberOfiPhones[“vader”] // nil // vadersPhones is an Optional -
Optionals You use optionals in situations where a value may
be absent. An optional says: • There is a value, and it equals x • There isn’t a value at all • Only -
Optionals • The concept of optionals doesn’t exist in C
or Objective-C. The nearest thing in Objective-C is the ability to return nil • However, this only works for objects - it doesn’t work for structures, basic C types, or enumeration values. Requires NSNotFound or something. • Optionals in Swift work for everything -
Optionals var vaders: Int? = forceAwakensCharacters[“vader”] if(vaders == nil) {
// do something } else { let count: Int = vaders! } if(vadersPhones) { let count: Int = vaders! } -
Optionals let cast = ["luke": 1, "wookie": 2] var vader
: Int? = cast["vader"] if let vader = cast["vader"] { // Optional Binding } guard let vader = cast["vader"] else { break } var vader2: Int = cast["vader"]! -
Optionals Note: Trying to use ! to access a non-existent
optional value triggers a runtime error. Always make sure that an optional contains a non-nil value before using ! to force-unwrap its value. -
If statements if myVar { print(“myVar, hurray!”) } else if
herVar { } if(myVar) { } // braces are required -
Tuples • Tuples group multiple values into a single compound
value • The values within a tuple can be of any type and do not have to be of the same type as each other. -
Tuples let http404Error = (404, "Not Found") // (Int, String)
let (statusCode, statusMessage) = http404Error print("The status code is \(statusCode)") // prints "The status code is 404" print("The status message is \(statusMessage)") // prints "The status message is Not Found” -
Tuples let http200Status = (statusCode: 200, description: "OK") print("The status
code is \(http200Status.statusCode)") // prints "The status code is 200" print("The status message is \(http200Status.description)") // prints "The status message is OK -
Switch statements switch phoneCount { case 1: print(“One phone”) case
2,3,4: print(“More phones”) default: break } switch phoneCount { case [0, 1, 2]: print(“One phone”) case 3...6: print(“More phones”) default: break } -
Switch staments // There’s more! switch sender { case myTextField:
print(“Text”) case myButton: print(“Button”) default: break } -
Functions func helloWorld(name: String = “John”) { print(“Hello world \(name)”);
} helloWorld() // prints ‘Hello World John’ -
Functions func helloWorld(name: String = “John”) -> String { return
“Hello world \(name)”; } let a: String = helloWorld() -
Closures • Closures are self-contained blocks of functionality that can
be passed around and used in your code. • Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages. -
Closures Closure expression syntax has the following general form: {
(parameters) -> return type in statements } -
Closures let helloSayer: () -> () in { print(“Hello World”)
} func doTask(task: () -> ()) { } doTask(helloSayer) doTask { print(“Hello”) } -
Classes - Swift has no universal base class - No
#import “Bla.h” - Type inference - ARC -
Properties in Classes class Animal { // methods // properties
// initializers } class Cat : Animal { var ears = 2 // property } -
Properties in Classes class Cat { var description: String {
get { return “Cat Description” } set { } } } let someCat = Cat() -
Initializers & Overriding class Aegean : Cat { var ears
init() { super.init() ears = 3 } override var someFunction: String { get { return “Cat Function” } } -
Property Observers class Cat { init() { mouth = “Big”
} var mouth : String { willSet { // old value available here } didSet { // new value available here } } -
Methods class Aegean : Cat { func jump(amount: Int) {
for int i = 0; i < amount; i++ { print(“jump”) } } } -
Error handling You use error handling to respond to error
conditions your program may encounter during execution • Determine the underlying cause of failure unlike optionals which only communicate the presence of a failure -
Error handling func canThrowAnError() throws { // this function may
or may not throw an error } do { try canThrowAnError() // no error was thrown } catch { // an error was thrown } -
Getting started https://swift.org/getting-started/ Ray Tutorial OSX & Linux support No
Cocoa for Linux ( ͡° ͜ʖ ͡°) -
Getting started Interesting cocoa free repos Epoch // HTTP server
for Swift 2.2 on Linux Coolie // Coolie helps you to create models (& their constructors) from JSON file Style guide