Swift. Introducing swift. Thomas Woodfin

Similar documents
Introduction to Programming Using Java (98-388)

Porting Objective-C to Swift. Richard Ekle

Questions. Exams: no. Get by without own Mac? Why ios? ios vs Android restrictions. Selling in App store how hard to publish? Future of Objective-C?

Xcode 6 and ios 8 What s New for Software Developers

SWIFT! init(title: String) { self.title = title } // required initializer w/ named parameter

Scala : an LLVM-targeted Scala compiler

Introduction to Swift. Dr. Sarah Abraham

ios Application Development Lecture 2: Seminar and Unit 1

Mobile Application Programming. Swift Classes

Index. object lifetimes, and ownership, use after change by an alias errors, use after drop errors, BTreeMap, 309

SWIFT BASICS

Visual C# Instructor s Manual Table of Contents

IBM Case Manager Mobile Version SDK for ios Developers' Guide IBM SC

ITP 342 Mobile App Dev. Functions

Chapter 2: Using Data

SPARK-PL: Introduction

ITP 342 Mobile App Dev. Strings

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Mobile Application Programming. Swift Classes

GaE Graphs Ain t Easy. Andrew Jones (adj2129) Kevin Zeng (ksz2109) Samara Nebel (srn2134)

SWIFT - CLOSURES. Global Functions Nested Functions Closure Expressions. Have a name. Capture values from enclosing function

Worksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords

Functions and Collections. Dr. Sarah Abraham

Python - Variable Types. John R. Woodward

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

Advanced Algorithms and Computational Models (module A)

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++

CSC Web Programming. Introduction to JavaScript

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

The Pyth Language. Administrivia

Try the following example using Try it option available at the top right corner of the following sample code box:

Xcode & Swift: Introduction

COMP-520 GoLite Tutorial

Beyond Blocks: Python Session #1

Review (Basic Objective-C)

Type Conversion. and. Statements

CS 4240: Compilers and Interpreters Project Phase 1: Scanner and Parser Due Date: October 4 th 2015 (11:59 pm) (via T-square)

Recap: Functions as first-class values

Mobile Application Development

Python Evaluation Rules

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

A Fast Review of C Essentials Part I

Data Structures (list, dictionary, tuples, sets, strings)

CMSC 330: Organization of Programming Languages. Rust Basics

Chapter 2 Welcome App

Lab 7: OCaml 12:00 PM, Oct 22, 2017

Python in 10 (50) minutes

iphone Application Programming Lecture 3: Swift Part 2

Index COPYRIGHTED MATERIAL

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments

STRUCTURING OF PROGRAM

PHP. Interactive Web Systems

Glossary. For Introduction to Programming Using Python By Y. Daniel Liang

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Control Structures. A program can proceed: Sequentially Selectively (branch) - making a choice Repetitively (iteratively) - looping

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

CSc Introduction to Computing

Functions & Variables !

PREPARING FOR THE FINAL EXAM

Java+- Language Reference Manual

Introductory ios Development

C++ (Non for C Programmer) (BT307) 40 Hours

Reverse Engineering Swift Apps. Michael Gianarakis Rootcon X 2016

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

Senthil Kumaran S

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

DSC 201: Data Analysis & Visualization

Using Scala for building DSL s

Issue with Implementing PrimeSieve() in Go

CS 360: Programming Languages Lecture 10: Introduction to Haskell

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017


Introduction to Python

Rule 1-3: Use white space to break a function into paragraphs. Rule 1-5: Avoid very long statements. Use multiple shorter statements instead.

CS304 Object Oriented Programming Final Term

Discover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs.

GNU ccscript Scripting Guide IV

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Python I. Some material adapted from Upenn cmpe391 slides and other sources

Begin at the beginning

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

The current topic: Python. Announcements. Python. Python

Richard Mallion. Swift for Admins #TEAMSWIFT

2 nd Week Lecture Notes

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

printf( Please enter another number: ); scanf( %d, &num2);

ios: Objective-C Primer

C# Fundamentals. Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh

Maxime Defauw. Learning Swift

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter 2: Basic Elements of C++

Stanford CS193p. Developing Applications for ios. Fall CS193p. Fall

Statements 2. a operator= b a = a operator b

BEGINNING ios PROGRAMMING

Lecture 2 Tao Wang 1

Java Identifiers. Java Language Essentials. Java Keywords. Java Applications have Class. Slide Set 2: Java Essentials. Copyright 2012 R.M.

Transcription:

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