Swift Introducing swift Thomas Woodfin
Content Swift benefits Programming language Development Guidelines
Swift benefits What is Swift Benefits
What is Swift New programming language for ios and OS X Development Announced at WWDC2014 after being worked on in secret for 4 years. Used to write application for ios 7+ and OS X Mavericks+. Xcode 6 includes Swift support. Work with Object-C It s possible to add swift to existing Object-C program and allow call methods existing Object-c libraries. Designed to be succinct
Benefits Apps run faster Read-Eval-Print-Loop (REPL): The debugging console in Xcode includes an interactive version of the Swift language built using the newest LLVM compiler. Processing Speed: Optimize the native code to reduce the time needed to compile in real-time. Creating and modifying apps can be done in less time, resulting in faster deployment. Elimination of the need to end every command with a semi-colon. Inferred types eliminate the requirement to specify the variable type. Automatic memory management. Interactive playgrounds let developers view the results of code as it is entered, simplifying debugging and testing. Compatible with Objective-C, allowing integration with existing apps without the need to reinvent the wheel.
Programming language Constant & Variables Data types Control Flow Functions Class Generics
Constant & Variables Definition syntax Defining constant or variables is simple in Swift language, use keyword let to define for constant and var to define for variables.
Constant & Variables (Cont) Don t require to specify the type with constant and variables. The compiler automatically detected it based on value that you have assigned to them. Optionals Optionals indicate that a constant or variable allowed to have no value. An optional is written as?. The question mark indicates that the value it contains is optional, meaning that it might contain some value, or it might contain no value.
Constant & Variables (Cont) If you define an optional constant or variable without providing a default value, the constant or variable is automatically set to nil:
Data types Integers Int UInt Float point Float Double Boolean Bool
Data types Type conversion Let s check example in Object-C In Swift you can t do that. You have to decide the type of result statements (it means variables in statements be in same type)
Data types - Tuples Group multiple values into a single compound value. You can pass a tuples as a method parameter, return it from a function (or method). Definition syntax: var repsonse: (Int, String) Assign value to tuples repsonse = (10, your value ) Tuples values can be access through their index number or names.
Data types Tuples (Cont) Accessing the value through its zero-based index. You can decompose a tuple s contents into separate constants or variables, which you then access as usual:
Data types- Strings Definition syntax var companyname = Quantic Mutability In this case you use var keyword to define a String, then it is mutable (can be modified). Use let keyword to define, then it is immutable (can not be modified)
Data types- Strings (Cont) Example: var variablestring = "Horse" variablestring += " and carriage" // variablestring is now "Horse and carriage" let constantstring = "Highlander" constantstring += " and another Highlander" // this reports a compile-time error - a constant string cannot be modified Comparison Swift provides three ways to compare string: string and character equality, prefix equality, and suffix equality.
Data types- Strings (Cont) String and character equality Use == operator to check equal to and!= operator to check not equal to let yourname = Your name here let sameyourname = " Your name here if yourname == sameyourname { println("that two strings are equal") } Prefix and suffix equality To check whether a string has a particular string prefix or suffix, call the string s hasprefix and hassuffix methods, both of which take a single argument of type String and return a Boolean value.
Data types- Strings (Cont) Concatenating Strings and Characters String values can be added together (or concatenated) with operator (+) to create a new String value: let string1 = "hello" let string2 = " there" var welcome = string1 + string2 You can also append a String value to an existing String variable with operator (+=): var instruction = "look over" instruction += string2
Data types- ARRAYS Stores multiple values of the same type in an ordered list. Definition syntax: let arr: Array<String> = [ val1, val2, etc ] //or Shorthand Syntax let arr : [String] = [ val1, val2, etc ] //or let arr = [ val1, val2, etc ] Access and modify array content
Data types- ARRAYS (Cont) let arr = [ val1, val2, val2 ] println(arr[0]) // Print console first element of array arr[0] = newval1 Note that the first item in the array has an index of 0, not 1. Arrays in Swift are always zero-indexed. You can add a new item to the end of an array by calling the array s append method: arr.append( append new value ) Alternatively, append an array of one or more compatible items with the addition assignment operator (+=): arr += [ val3, val4 ]
Data types- DICTIONARIES Stores multiple values of the same type. Each value is associated with a unique key Definition syntax: let dict : Dictionary<String, Int> = [ A : 1, B : 2] //Or Shorthand Syntax let dict : [String : Int] = [ A : 1, B : 2] //Or let dict = [ A : 1, B : 2] Access and modify dictionary content
Data types- DICTIONARIES (Cont) let dict : Dictionary<String, Int> = [ A : 1, B : 2] println(dict[ A ])// Print value of key A You can add a new item to a dictionary with syntax dict[ C ] = 3 // Add new Key: Value pairs to the dictionary You can also use the syntax to change the value associated with a particular key dict[ A ] = 2 // Modify the value of key A Remove a key-value pair from a dictionary with the removevalueforkey method dict. removevalueforkey( A )//Remove key A and its value
Control Flow IF Switch Loops
Control Flow - IF You don t have to add parentheses around the condition. In case complex conditions, you should use them. Conditions must be BooleanType (True or false). You can t check variable directly like Object-C
Control Flow - SWITCH Works like many other languages but with some new features and small differences: Support any kind of data, not only integer. No need for break statements.
Control Flow SWITCH (Cont) Each case must contain at least one executable statement. Multiple matches for a single switch case can be separated by commas.
Control Flow SWITCH (Cont)
Control Flow SWITCH (Cont) You can also use the range of values for checking in case. Ranges are identified You can use tuples to test multiple values in the same switch statement. Each element of the tuple can be tested against a different value or range of values. Alternatively, use the underscore (_) identifier to match any possible value
Control Flow SWITCH (Cont) A switch case can blind the values of variable to temporary constants or variable and use it in the body of the case.
Control Flow SWITCH (Cont) A switch case can use a where clause to check for additional conditions.
Control Flow - LOOPS Work like many other languages but with some small differences: Don t have to write the parentheses. For-in loop to iterate over collections of data. Also it can be used with ranges.
Functions Functions is created using key word func. In parameters: name and type of variable between : You can describe or name variable parameters of the function by writing the name before it or add # if it is already an appropriate name to use.
Functions (Cont) Function parameters are constant by default and you can t change value them.
Functions (Cont) To change variable parameters in function: you have to copy the values to other variables OR write var before the name
Functions (Cont) If you want a function to modify a parameter s value, and you want those changes to persist after the function call has ended, define that parameter as an in-out parameter instead.
Functions (Cont) To return values in function, you have to write type of returned info after () and -> Functions can take variable number of arguments using
Functions (Cont) In Swift, functions are first-class type, so you can pass it as parameter or return it as a result.
Class Swift is object oriented language and you can create your own custom classes. Unlike other programming languages, Swift does not require you to create separate interface and implementation files for custom classes. You define a class in a single file. To create a class, you use keyword class and then you can list all properties and methods of class.
Class (Cont) In creating new instance of your class, you don t use keyword like Object-C: new, alloc, init. Just the class name and parentheses (). Class instances are passed by reference types.
Class (Cont)
Class (Cont) In Swift, a class can inherit from another class using : Calling super is required when you override any initializer from super class. Use keyword override when you want to override a function from your super class.
Class (Cont)
Class (Cont) All properties in example above called stored properties, because we use it to store values. Stored properties can be either variable stored properties or constant stored properties. In Swift, we have other type called Computed properties as that properties don t store anything but we compute the value from other properties. They provide a getter and an optional setter to retrieve and set other properties and values indirectly.
Class (Cont)
Class (Cont) Type method in Swift is a way to define methods that are called on the type itself. You indicate type methods for classes by writing the keyword class before the method s func keyword.
Class (Cont)
Generics Generic code enables you to write flexible, reusable functions and types that can work with any type. Generics are used to allow you to use the same code for different types. For example, Swift s Array and Dictionary types are both generic collections.
Generics (cont)
Development Guidelines Install & Using development tool Demo Application
Install & Using development tool To develop ios apps in Swift, you need: A Mac computer running OS X 10.9.4 or later Xcode (latest version) ios SDK To download the latest version of Xcode
Install & Using development tool Create New project with Swift Open Xcode from the /Applications directory. The Xcode welcome window appears.
Install & Using development tool
Install & Using development tool In the welcome window, click Create a new Xcode project (or choose File > New > Project). Xcode opens a new window and displays a dialog in which you choose a template.
Install & Using development tool
Install & Using development tool In the ios section at the left of the dialog, select Application. In the main area of the dialog, click Single View Application and then click Next. In the dialog that appears, name your app and choose additional options for your project.
Install & Using development tool
Install & Using development tool Click Next. In the dialog that appears, choose a location to save your project and click Create. Xcode opens your new project in a window (called the workspace window):
Install & Using development tool
Install & Using development tool Now you can run the project on ios simulator. Click on run button and look.
Install & Using development tool
Demo Application Basic UI Mix Swift code and Object-C code
Mix Swift code and Object-C code Objective-C and Swift files can coexist in a single project, whether the project was originally an Objective-C or Swift project. You can simply add a file of the other language directly to an existing project.
Mix Swift code and Object-C code
Mix Swift code and Object-C code 1. Importing Objective-C into Swift To import Objective-C files into your Swift code, you rely on an Objective-C bridging header to expose those files to Swift. Xcode offers to create this header file when you add a Swift file to an existing Objective-C app, or an Objective-C file to an existing Swift app.
Mix Swift code and Object-C code
Mix Swift code and Object-C code If you accept, Xcode creates the header file with names it by your product module name followed by adding -Bridging-Header.h
Mix Swift code and Object-C code How to import Objective-C code into Swift code In your project, open bridging header file, import every Objective-C header you want to use in Swift.
Mix Swift code and Object-C code In Build Settings, make sure the Objective-C Bridging Header was set under Swift Compiler - Code Generation.
Mix Swift code and Object-C code 2. Importing Swift into Objective-C To import Swift code into Objective-C, you rely on an Xcode-generated header file. This automatically generated file is an Objective-C header that declares the Swift interfaces in your target. The name of this header is your product module name followed by adding "-Swift.h. The file is hidden, you can t see in your project.
Mix Swift code and Object-C code
Mix Swift code and Object-C code How to import Swift code into Objective- C code Import the Swift code into any Objective-C.m file using this syntax #import ProductModuleName- Swift.h
References Learn Swift www.tbltechnerds.com