Presentation is loading. Please wait.

Presentation is loading. Please wait.

KIT305/607 Mobile Application Development – Apple iOS Swift, Comparison of Swift and Objective-C, Swift Basics, Playgrounds, Persistent Storage Dr. Rainer.

Similar presentations


Presentation on theme: "KIT305/607 Mobile Application Development – Apple iOS Swift, Comparison of Swift and Objective-C, Swift Basics, Playgrounds, Persistent Storage Dr. Rainer."— Presentation transcript:

1 KIT305/607 Mobile Application Development – Apple iOS Swift, Comparison of Swift and Objective-C, Swift Basics, Playgrounds, Persistent Storage Dr. Rainer Wasinger, Dr. James Montgomery School of Engineering and ICT 1

2 Swift 2

3 3 A new programming language for iOS, OS X, watchOS, and tvOS apps, that builds on the best of C and Objective-C without the constraints of C compatibility. First introduced at Apple’s WWDC 2014 as Swift 1.0. Swift 2.0 was then released at WWDC 2015, and made available for publishing apps in the App Store in Sep.2015. It was originally a proprietary language, but v2.2 has been made open source under the Apache License 2 in Dec.2015.

4 Swift 4 Objective-C code compilation: Swift code compilation:

5 Comparison of Swift and Objective-C 5

6 6 Differences to Objective-C Statements do not need to end with a semicolon (though they must be used if multiple statements are on a single line). Header files are not required. Uses type inference Functions are first-class objects Enumeration cases can have associated data. Operators can be redefined for classes (operator overloading) and new operators can be created Strings fully support Unicode. No exception handling (prior to Swift 2.0). Multi-line comments can be nested.

7 7 Differences to Objective-C Error-prone behaviours of earlier c-family languages have been changed: Pointers are not exposed by default. Assignments do not return a value. No need to use break statements in switch blocks. Individual cases do not fall through to the next case unless the fallthrough statement is used. Variables and constants are always initialized and array bounds are always checked. Integer overflows are trapped as a runtime error in Swift. The single-statement form of if (to allow the omission of braces around the statement) is not supported.

8 Example: Hello World Objective-C: NSString*str = @"Hello World"; NSLog(@"%@", str); Swift: let str = "Hello World" print("\(str)" ) 8

9 Example: Arrays Objective-C: //Non-Mutable Array NSArray * myFixedArray = [[NSArray alloc] initWithObjects:@"Object1", @"Object2",nil]; //Mutable Array NSMutableArray * myFlexibleArray = [[NSMutableArray alloc]init]; //Add Object using Old Syntax [myFlexibleArray addObject:@"Object1"]; //Add Object using New Syntax myFlexibleArray[1] = @"Object2"; NSLog(@"myFixedArray: %@",myFixedArray); NSLog(@"myFlexibleArray: %@",myFlexibleArray); Swift: //Constant Array let myFixedArray: [String] = ["Object1", "Object1"] //Variable Array var myFlexibleArray = [String]() //Add Objects myFlexibleArray.append("Object1") myFlexibleArray.append("Object2") print("myFixedArray: \(myFixedArray)") print("myFlexibleArray: \(myFlexibleArray)") 9

10 Example: Dictionary Objective-C: //Non-Mutable Dictionary NSDictionary * myFixedDictionary = @{@"key1":@"value1", @"key2":@"value2"}; //Mutable Dictionary NSMutableDictionary * myFlexibleDictionary = [[NSMutableDictionary alloc]init]; //Set Object [myFlexibleDictionary setObject:@"value1" forKey:@"key1"]; NSLog(@"myFixedDictionary: %@",myFixedDictionary); NSLog(@"myFlexibleDictionary: %@",myFlexibleDictionary); Swift: //Constant Dictionary let myFixedDictionary = ["key1":"value1","key2":"value2"] //Variable Dictionary var myFlexibleDictionary = [String : String]() //Set Object myFlexibleDictionary["key1"] = "value1" myFlexibleDictionary["key2"] = "value2" print("myFixedDictionary: \(myFixedDictionary)") print("myFlexibleDictionary: \(myFlexibleDictionary)") 10

11 Swift Basics 11

12 12 Swift Basics Swift provides its own versions of all fundamental C and Objective-C types, including Int for integers, Double and Float for floating-point values, Bool for Boolean values, and String for textual data. Swift also provides powerful versions of the three primary collection types, Array, Set, and Dictionary, Swift makes extensive use of variables whose values cannot be changed. In Swift, these are known as constants. Swift introduces advanced types not found in Objective-C, such as tuples. Tuples allow groupings of values to be passed around, e.g. a tuple can be used to return multiple values from a function as a single compound value. Swift also introduces optional types, which handle the absence of a value. Using optionals is similar to using nil with pointers in Objective-C, but they work for any type, not just classes. Swift is a type-safe language, which means the language helps you to be clear about the types of values your code can work with

13 13 Constants and Variables Constants and variables associate a name with a value of a particular type. The value of a constant cannot be changed once it is set, whereas a variable can be set to a different value in the future. Constants and variables must be declared before they are used. Constants are declared with the let keyword and variables with the var keyword. //constant let maximumNumberOfLoginAttempts = 10 //var var currentLoginAttempt = 0

14 14 Type Annotations and Type Inference You can provide a type annotation when you declare a constant or variable, to be clear about the kind of values the constant or variable can store. This is done by placing a colon after the constant or variable name, followed by a space, followed by the name of the type to use. var welcomeMessage: String The colon in the declaration means “…of type…,”. Note: It is rare that you need to write type annotations in practice (in Swift). If you provide an initial value for a constant or variable at the point that it is defined, Swift can almost always infer the type to be used for that constant or variable.

15 Type Inference and Type Safety Swift is a type-safe language. Because Swift is type safe, it performs type checks when compiling your code and flags any mismatched types as errors. Swift uses type inference to work out the appropriate type. This enables a compiler to deduce the type of a particular expression automatically when it compiles your code. Because of type inference, Swift requires far fewer type declarations than languages such as C or Objective-C. Constants and variables are still explicitly typed, but much of the work of specifying their type is automatically. 15

16 Type Inference and Type Safety Examples: let meaningOfLife = 42 // meaningOfLife is inferred to be of type Int let pi = 3.14159 // pi is inferred to be of type Double let orangesAreOrange = true let turnipsAreDelicious = false 16

17 17 Naming Constants and Variables Constant and variable names can contain almost any character, including Unicode characters: let π = 3.14159 let 你好 = " 你好世界 " let = "dogcow" Constant and variable names cannot contain whitespace characters, mathematical symbols, arrows, private-use (or invalid) Unicode code points, or line- and box-drawing characters. Nor can they begin with a number, although numbers may be included elsewhere within the name.

18 18 Printing Constants and Variables You can print the current value of a constant or variable with the print(_:separator:terminator:) function: var friendlyWelcome = "Hello!" friendlyWelcome = "Bonjour!" print(friendlyWelcome) By default, the function terminates the line it prints by adding a line break. To print a value without a line break after it, pass an empty string as the terminator, e.g.: print(someValue, terminator: "") Swift uses string interpolation to include the name of a constant or variable as a placeholder in a longer string. To prompt Swift to replace it with the current value of that constant or variable, wrap the name in parentheses and escape it with a backslash before the opening parenthesis: print("The current value of friendlyWelcome is \(friendlyWelcome)")

19 19 Comments Comments in Swift are very similar to comments in C. Single-line comments begin with two forward-slashes (//): // this is a comment Multiline comments start with a forward-slash followed by an asterisk (/*) and end with an asterisk followed by a forward-slash (*/): /* this is also a comment, but written over multiple lines */ Unlike multiline comments in C, multiline comments in Swift can be nested inside other multiline comments. /* this is the start of the first multiline comment /* this is the second, nested multiline comment */ this is the end of the first multiline comment */ Nested multiline comments enable you to comment out large blocks of code quickly and easily.

20 20 Semicolons Unlike many other languages, Swift does not require you to write a semicolon (;) after each statement in your code, although you can do so if you wish. Semicolons are required if you want to write multiple separate statements on a single line: let cat = ""; print(cat)

21 21 New type - Tuples We’ve seen the types String, Int, Double, and Boolean in the examples above. Swift also has some new advanced types. One of these is called 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. let http404Error = (404, "Not Found") In the above example, http404Error is a tuple of type (Int, String), and equals (404, "Not Found").

22 New type - Tuples You can decompose a tuple’s contents into separate constants or variables, which you then access as usual: let (statusCode, statusMessage) = http404Error print("The status code is \(statusCode)") print("The status message is \(statusMessage)") If you only need some of the tuple’s values, ignore parts of the tuple with an underscore (_) when you decompose the tuple: let (justTheStatusCode, _) = http404Error print("The status code is \(justTheStatusCode)") 22

23 23 New type - Optionals You use optionals in situations where a value may be absent. An optional says: There is a value, and it equals x, or There isn’t a value at all. The concept of optionals doesn’t exist in C or Objective-C. The nearest thing in Objective-C is the ability to return nil from a method that would otherwise return an object, with nil meaning “the absence of a valid object.” This however only works for objects—it doesn’t work for structures, basic C types, or enumeration values. You set an optional variable to a valueless state by assigning it the special value nil: var serverResponseCode: Int? = 404 serverResponseCode = nil An optional Int is written as Int?, not Int. The question mark indicates that the value it contains is optional, meaning that it might contain some Int value, or it might contain no value at all.

24 24 Error Handling You use error handling to respond to error conditions your program may encounter during execution. When a function encounters an error condition, it throws an error. That function’s caller can then catch the error and respond appropriately. A function indicates that it can throw an error by including the throws keyword in its declaration. When you call a function that can throw an error, you prepend the try keyword to the expression. func canThrowAnError() throws { // this function may or may not throw an error } do { try canThrowAnError() // no error was thrown } catch { // an error was thrown }

25 25

26 Further Code Comparisons between Objective-C and Swift 26

27 Example: Variables and Constants Objective-C: Declaring variables: int highScore; NSString *playerName; Assigning to a variable: highScore = 1000; playerName = @"Oliver Kahn"; Declaring and assigning constants: NSString *const skyColor = @"Blue"; int const daysInYear = 365; Swift: var highScore: Int var playerName: String highScore = 1000 playerName = "Oliver Kahn" let skyColor = "Blue“ let daysInYear = 365 27

28 Example: Classes Objective-C: Defining a class: header (.h) file: @interface CustomClass : NSObject @end implementation (.m) file: @implementation CustomClass @end Creating a new class instance: CustomClass *instance = [[CustomClass alloc] init]; CustomClass *secondInstance = [CustomClass new]; Swift: Swift (.swift) file: class CustomClass { } var instance = CustomClass() 28

29 Example: Methods Objective-C: Declaring a method: In the header (.h) file - (int) getOdometerReading; In the implementation (.m) file - (int) getOdometerReading { return 50000; } Calling a method: SpecificCar *myCar = [[SpecificCar alloc] init]; [myCar getOdometerReading]; Swift: func getOdometerReading() -> Int { return 50000 } var myCar = SpecificCar() myCar.getOdometerReading() 29

30 Example: Methods Objective-C: Declaring a method with multiple parameters: - (void)changeEngineOil:(int)oil transmissionFluid:(int)fluid { } Calling a method with multiple parameters: [myCar changeEngineOil:10 transmissionFluid:10]; Swift: func changeEngineOil(oil:Int, transmissionFluid:Int) { } myCar.changeEngineOil(10, transmissionFluid:10) 30

31 Example: Properties Objective-C: Declaring a property: In the implementation (.m) file: @interface SpecificCar () @property NSString *transmission; @property int numberOfSeats; @end @implementation SpecificCar - (id)init { self = [super init]; if (self) { self.transmission = @"Automatic"; self.numberOfSeats = 4; } return self; } @end Swift: class Specific:Car { var transmission: String = "Automatic" var numberOfSeats: Int init() { self.numberOfSeats = 4 super.init() } } 31

32 Example: For Loop with Range Operator Objective-C: Writing a for loop: for (int i = 0; i < 10; i++) { } NSArray *array = @[@"item 1", @"item 2"]; for (NSString *item in array) { } Swift: for var i = 0; i < 10; i++ { } for i in 0..10 { } var array = ["item 1", "item 2"] for item in array { } 32

33 Example: Switch statements Objective-C: int numberOfPeople = 1; switch (numberOfPeople) { case 1: // code for this case break; case 2: // code for this case break; default: // code for this case break; } Swift: var numberOfPeople = 1 switch numberOfPeople { case 1: // code for this case case 2: // code for this case default: // code for this case } var carMake = "Toyota" switch carMake { case "Toyota": // code for this case case "Honda": // code for this case case "Nissan", "Subaru": // code for //this case default: // code for this case } 33

34 Example: Protocols Objective-C: Declaring a protocol: @protocol SampleProtocol - (void)someMethod; @end Conforming to a protocol: @interface MyClass : NSObject @end Swift: protocol SampleProtocol { func someMethod() } class MyClass: SampleProtocol { // Conforming to SampleProtocol func someMethod() { } } 34

35 Example: Delegation Objective-C: Declaring a delegate property: @interface FirstClass : NSObject @property (nonatomic, weak) id delegate; @end Calling a delegate property: if (self.delegate) [self.delegate someMethod]; Swift: class FirstClass { var delegate:SampleProtocol? } delegate?.someMethod() 35

36 Playgrounds Demo 36

37 37

38 Persistent Storage 38

39 39 Persistent Storage The OS installs each iOS application in a sandbox directory containing the application bundle directory and three additional directories, Documents, Library, and tmp. The tmp directory should only be used for temporarily storing files. The OS may empty this directory at any time, e.g. when the device is low on disk space. The Documents directory is for user data. The Library directory is for application data. The application’s sandbox directory can be accessed by calling the Foundation function: NSHomeDirectory().

40 Persistent Storage Several options exist to save persistent data: User Defaults and Property Lists Reading and Writing Strings to File SQLite Core Data 40

41 User Defaults and Property Lists NSUserDefaults is a property list (aka plist) where an application can store simple data. Although there is no limit to its size (aside from the device’s available memory), you should not store a large amount of data here. The file is written and read atomically, so the more data, the longer it will take to write and read. Property Lists can only accept certain types of variables, i.e.: NSArray, NSData, NSDictionary, NSNumber, and NSString. And NSArray and NSDictionary can themselves only contain the types listed above. 41

42 NSUserDefaults Objective-C: NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; //Saving to NSUserDefaults [defaults setInteger:3 forKey:@"MyIntKey"]; [defaults setObject:@"my string" forKey:@"MyStringKey"]; [defaults synchronize]; //Reading from NSUserDefaults NSInteger myInt = [defaults integerForKey:@"MyIntKey"]; NSString *myString = [defaults stringForKey:@"MyStringKey"]; //Print out the values NSLog(@“%d", myInt); NSLog(@“%@", myString); Swift: let defaults = NSUserDefaults.standardUserDefaults() //Saving to NSUserDefaults defaults.setInteger(3, forKey: "MyIntKey") defaults.setObject("my string", forKey: "MyStringKey") defaults.synchronize() //Reading from NSUserDefaults defaults.integerForKey("MyIntKey") defaults.objectForKey("MyStringKey") //Print out the value print(myInt) print(myString) 42

43 Writing Strings to File (Objective-C) Writing to a file: NSString *content = @"Line1: Text to write to file.\nLine2: More text.\nLine3: Even more text.\n"; NSError *error = NULL; NSString *docPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/data.txt"]; BOOL success = [content writeToFile:docPath atomically:YES encoding:NSUTF8StringEncoding error:&error]; if(success == NO) { NSLog( @"Error saving to %@ - %@", docPath, [error localizedDescription] ); } 43

44 Reading Strings from File (Objective-C) Reading from a file: //Get a reference to the file NSString *stringFromFile = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/data.txt"]; //Read the contents into a string NSString *myFile = [[NSString alloc] initWithContentsOfFile:stringFromFile encoding:NSUTF8StringEncoding error:nil]; // display contents NSLog(@"The file contains this: %@", myFile); // split string into an array NSArray *mySplit = [myFile componentsSeparatedByString:@"\n"]; // display just one item in the array NSLog(@"Index 0: %@", [mySplit objectAtIndex:0]); 44

45 Reading and Writing Strings to File (Swift) Writing to a file: let writeString = "Line1: Text to write to file.\nLine2: More text.\nLine3: Even more text.\n" let filePath = NSHomeDirectory() + "/Documents/data.txt" do { _ = try writeString.writeToFile(filePath, atomically: true, encoding: NSUTF8StringEncoding) } catch let error as NSError { print(error.description) } Reading from a file: var readString: String do { readString = try NSString(contentsOfFile: filePath, encoding: NSUTF8StringEncoding) as String print(readString) } catch let error as NSError { print(error.description) } 45

46 SQLite and Core Data SQLite SQLite is a library that implements a lightweight embedded relational database. It’s based on the SQL standard (Structured Query Language) just like MySQL and PostgreSQL. Using SQLite on iOS requires use of C-based libraries, though one object-oriented alternative solution is to use the Objective-C wrapper for SQLite called FMDB. URL: https://github.com/ccgus/fmdbhttps://github.com/ccgus/fmdb 46

47 SQLite and Core Data Core Data: Core Data provides a relational object-oriented model that can be serialized into an XML, binary, or SQLite store. The advantage of using Core Data is that you work with objects instead of raw data (e.g. rows in an SQLite database or data stored in an XML file). There is also a Core Data model editor built into Xcode. 47


Download ppt "KIT305/607 Mobile Application Development – Apple iOS Swift, Comparison of Swift and Objective-C, Swift Basics, Playgrounds, Persistent Storage Dr. Rainer."

Similar presentations


Ads by Google