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

Slides:



Advertisements
Similar presentations
Lecture 2 Introduction to C Programming
Advertisements

 2005 Pearson Education, Inc. All rights reserved Introduction.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Chapter 10.
Lecture-5 Though SQL is the natural language of the DBA, it suffers from various inherent disadvantages, when used as a conventional programming language.
VBA Modules, Functions, Variables, and Constants
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
Chapter 2: Introduction to C++.
Guide To UNIX Using Linux Third Edition
Introduction to C Programming
Basic Elements of C++ Chapter 2.
1 Chapter One A First Program Using C#. 2 Objectives Learn about programming tasks Learn object-oriented programming concepts Learn about the C# programming.
A First Program Using C#
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
JavaScript, Fifth Edition Chapter 1 Introduction to JavaScript.
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
CSC204 – Programming I Lecture 4 August 28, 2002.
C Derived Languages C is the base upon which many build C++ conventions also influence others *SmallTalk is where most OOP comes Java and Javascript have.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
CPS120: Introduction to Computer Science
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Programming Fundamentals. Today’s Lecture Why do we need Object Oriented Language C++ and C Basics of a typical C++ Environment Basic Program Construction.
Variables and ConstantstMyn1 Variables and Constants PHP stands for: ”PHP: Hypertext Preprocessor”, and it is a server-side programming language. Special.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Chapter 15 Introduction to PL/SQL. Chapter Objectives  Explain the benefits of using PL/SQL blocks versus several SQL statements  Identify the sections.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
Data TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 2: Introduction to C++
Python Functions.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process.
Copyright Curt Hill Variables What are they? Why do we need them?
Python Primer 1: Types and Operators © 2013 Goodrich, Tamassia, Goldwasser1Python Primer.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Programming Fundamentals. Overview of Previous Lecture Phases of C++ Environment Program statement Vs Preprocessor directive Whitespaces Comments.
Persistence CS 344 Mobile App Development Robert Muller.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Part:2.  Keywords are words with special meaning in JavaScript  Keyword var ◦ Used to declare the names of variables ◦ A variable is a location in the.
CSC 143A 1 CSC 143 Introduction to C++ [Appendix A]
Basic Scripting & Variables Yasar Hussain Malik - NISTE.
Swift. Introduced in 2014 Replaces Objective-C as “recommended development language” “safer, succinct, readable” Emphasizes type safety.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2 Introduction to C++
Java Basics. Tokens: 1.Keywords int test12 = 10, i; int TEst12 = 20; Int keyword is used to declare integer variables All Key words are lower case java.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
Dr. Abdullah Almutairi Spring PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used,
Chad’s C++ Tutorial Demo Outline. 1. What is C++? C++ is an object-oriented programming (OOP) language that is viewed by many as the best language for.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Java and C# - Some Commonalities Compile into machine-independent, language- independent code which runs in a managed execution environment Garbage Collection.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Programming for Mobile Technologies
Introduction to C++.
The Complete Guide For Programming Language Part 1
Introduction to C++ Programming
CMSC 202 Java Primer 2.
Python Primer 1: Types and Operators
Chapter 2: Introduction to C++.
Chap 2. Identifiers, Keywords, and Types
Presentation transcript:

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

Swift 2

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 It was originally a proprietary language, but v2.2 has been made open source under the Apache License 2 in Dec.2015.

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

Comparison of Swift and Objective-C 5

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 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.

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

Example: Arrays Objective-C: //Non-Mutable Array NSArray * myFixedArray = [[NSArray //Mutable Array NSMutableArray * myFlexibleArray = [[NSMutableArray alloc]init]; //Add Object using Old Syntax [myFlexibleArray //Add Object using New Syntax myFlexibleArray[1] 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

Example: Dictionary Objective-C: //Non-Mutable Dictionary NSDictionary * myFixedDictionary = //Mutable Dictionary NSMutableDictionary * myFlexibleDictionary = [[NSMutableDictionary alloc]init]; //Set Object [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

Swift Basics 11

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 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 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.

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

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

17 Naming Constants and Variables Constant and variable names can contain almost any character, including Unicode characters: let π = 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 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 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 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 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").

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

Further Code Comparisons between Objective-C and Swift 26

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

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

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 } var myCar = SpecificCar() myCar.getOdometerReading() 29

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

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

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

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

Example: Protocols Objective-C: Declaring a SampleProtocol - Conforming to a MyClass : Swift: protocol SampleProtocol { func someMethod() } class MyClass: SampleProtocol { // Conforming to SampleProtocol func someMethod() { } } 34

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

Playgrounds Demo 36

37

Persistent Storage 38

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().

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

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

NSUserDefaults Objective-C: NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; //Saving to NSUserDefaults [defaults setInteger:3 [defaults string" [defaults synchronize]; //Reading from NSUserDefaults NSInteger myInt = [defaults NSString *myString = [defaults //Print out the values myInt); 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

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

Reading Strings from File (Objective-C) Reading from a file: //Get a reference to the file NSString *stringFromFile = [NSHomeDirectory() //Read the contents into a string NSString *myFile = [[NSString alloc] initWithContentsOfFile:stringFromFile encoding:NSUTF8StringEncoding error:nil]; // display contents file contains this: myFile); // split string into an array NSArray *mySplit = [myFile // display just one item in the array 0: [mySplit objectAtIndex:0]); 44

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

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: 46

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