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

Similar documents
SWIFT - FUNCTIONS. Function Declaration: It tells the compiler about a function's name, return type, and parameters.

iphone Application Programming Lecture 3: Swift Part 2

SWIFT - METHODS. In Swift language, Classes, Structures and Enumeration instances are accessed through the instance methods.

The SPL Programming Language Reference Manual

Assignment: 1. (Unit-1 Flowchart and Algorithm)

COMP519 Web Programming Lecture 27: PHP (Part 3) Handouts

ITP 342 Mobile App Dev. Functions

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

C# MOCK TEST C# MOCK TEST I

iphone Application Programming Lecture 3: Swift Part 2

Lecture 3 Tao Wang 1

Swift. Introducing swift. Thomas Woodfin

COMP327 Mobile Computing Session:

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

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

Scala : an LLVM-targeted Scala compiler

egrapher Language Reference Manual

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

CS242 COMPUTER PROGRAMMING

CSI33 Data Structures

Chapter 4: Control structures. Repetition

The PCAT Programming Language Reference Manual

Xcode & Swift: Introduction

Cellular Automata Language (CAL) Language Reference Manual

Pace University. Fundamental Concepts of CS121 1

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

Using Boolean Expressions. Multiway Branches. More about C++ Loop Statements. Designing Loops. In this chapter, you will learn about:

UNIT- 3 Introduction to C++

Chapter 4: Control structures

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Case by Case. Chapter 3

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators

JAVASCRIPT - OBJECTS OVERVIEW

C# MOCK TEST C# MOCK TEST II

Functional Programming Languages (FPL)

Products and Records

PHP. Interactive Web Systems

Introduction. C provides two styles of flow control:

The Warhol Language Reference Manual

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode

Inductive Data Types

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Lexical Considerations

10. Functions (Part 2)

Programming, numerics and optimization

GNU ccscript Scripting Guide IV

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

CSc Introduction to Computing

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Decaf Language Reference Manual

Do not start the test until instructed to do so!

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Haskell Functions

Short Notes of CS201

COMP284 Scripting Languages Lecture 11: PHP (Part 3) Handouts

FRAC: Language Reference Manual

easel LANGUAGE REFERENCE MANUAL

7.1 Optional Parameters

Introduction to Computer Science Midterm 3 Fall, Points

CS201 - Introduction to Programming Glossary By

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

CSCI 1061U Programming Workshop 2. C++ Basics

CSE 341 Section 5. Winter 2018

1 Lexical Considerations

CSC Web Programming. Introduction to JavaScript

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

Topic IV. Parameters. Chapter 5 of Programming languages: Concepts & constructs by R. Sethi (2ND EDITION). Addison-Wesley, 1996.

CSC Web Programming. Introduction to SQL

Haskell Types COMP360

Chapter-8 DATA TYPES. Introduction. Variable:

(Refer Slide Time: 4:00)

SWIFT - PROTOCOLS. Protocols also follow the similar syntax as that of classes, structures, and enumerations:

RSL Reference Manual

Specifying Syntax. An English Grammar. Components of a Grammar. Language Specification. Types of Grammars. 1. Terminal symbols or terminals, Σ

PROGRAMMING IN HASKELL. Chapter 5 - List Comprehensions

Part IV. Behavioural Description Using VHDL

Exceptions, Case Study-Exception handling in C++.

Issue with Implementing PrimeSieve() in Go

Topic IV. Block-structured procedural languages Algol and Pascal. References:

XQ: An XML Query Language Language Reference Manual

CS Programming Languages: Scala

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

JavaScript: Sort of a Big Deal,

Functions. Arash Rafiey. September 26, 2017

Chapter 4: Making Decisions

Data Types, Variables and Arrays. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

G Programming Languages - Fall 2012

COBOL - TABLE PROCESSING

SCALA ARRAYS. Following picture represents array mylist. Here, mylist holds ten double values and the indices are from 0 to 9.

Classes. Logical method to organise data and functions in a same structure. Also known as abstract data type (ADT).

learning objectives learn about variables, their types and their values learn about different number representations

CSc 520 Principles of Programming Languages

CSci 4223 Lecture 12 March 4, 2013 Topics: Lexical scope, dynamic scope, closures

7. Introduction to Denotational Semantics. Oscar Nierstrasz

Begin at the beginning

CISC-124. Casting. // this would fail because we can t assign a double value to an int // variable

The sequence of steps to be performed in order to solve a problem by the computer is known as an algorithm.

Chapter 4: Making Decisions

Recap: Functions as first-class values

CS111: PROGRAMMING LANGUAGE II

9691 COMPUTING. 9691/23 Paper 2 (Written Paper), maximum raw mark 75

Transcription:

http://www.tutorialspoint.com/swift/swift_closures.htm SWIFT - CLOSURES Copyright tutorialspoint.com Closures in Swift are similar to that of self-contained functions organized as blocks and called anywhere like C and Objective C languages. Constants and variable references defined inside the functions are captured and stored in closures. Functions are considered as special cases of closures and it takes 3 forms. Global Functions Nested Functions Closure Expressions Have a name. Do not capture any values Have a name. Capture values from enclosing function Unnamed Closures capture values from the adjacent blocks Closure expressions in Swift language follows crisp, optimization and light weight syntax styles which includes. Syntax Inferring parameter and return value types from context. Implicit returns from single-expression closures. Shorthand argument names and Trailing closure syntax Following is a generic syntax to define closure which accepts parameters and returns a data type: {(parameters) -> return type in statements Following is a simple example: let studname = { println("welcome to Swift Closures") studname() Welcome to Swift Closures Following closure accepts two parameters and return a Bool value: {(Int, Int) -> Bool in Statement1 Statement 2 --- Statement n Following is a simple example: let divide = {(val1: Int, val2: Int) -> Int in return val1 / val2 let result = divide(200, 20) println (result)

10 Expressions in Closures Convenient way of naming and defining blocks of code are achieved through nested functions. Instead of representing the whole function declaration and name constructs are used to denote shorter functions. Representing the function in a clear brief statement with focused syntax is achieved through closure expressions. Ascending Order Program Sorting a string is achieved by the Swifts key reserved function "sorted" which is already available in the standard library. The function will sort the given strings in the ascending order and returns the elements in a new array with same size and data type mentioned in the old array. The old array remains the same. Two arguments are represented inside the sorted function Values of Known type represented as arrays. Array contents Int, Int and returns a Boolean value Bool if the array is sorted properly it will return true value otherwise it will return false. Normal function with input string is written and passed to the sorted function to get the strings sorted to new array which is shown below func ascend(s1: String, s2: String) -> Bool { return s1 > s2 let stringcmp = ascend("swift", "great") println (stringcmp) true The initial array to be sorted for icecream is given as "Swift" and "great". Function to sort the array is declared as string datatype and its return type is mentioned as Boolean. Both the strings are compared and sorted in ascending order and stored in a new array. If the sorting is performed successful the function will return a true value else it will return false. Closure expression syntax uses constant parameters. variable parameters and inout parameters. Closure expression did not support default values. Variadic parameters and Tuples can also be used as parameter types and return types. let sum = {(no1: Int, no2: Int) -> Int in return no1 + no2 let digits = sum(10, 20) println(digits) 30 The parameters and return type declarations metioned in the function statement can also be represented by the inline closure expression function with 'in' keyword. Once declaring parameter

and return types 'in' keyword is used to denote that the body of the closure. Single Expression Implicit Returns Here, the function type of the sorted function's second argument makes it clear that a Bool value must be returned by the closure. Because the closure's body contains a single expression s1 > s2 that returns a Bool value, there is no ambiguity, and the return keyword can be omitted. To return a Single expression statement in expression closures 'return' keyword is omitted in its declaration part. let count = [5, 10, -6, 75, 20] var descending = sorted(count, { n1, n2 in n1 > n2 ) var ascending = sorted(count, { n1, n2 in n1 < n2 ) println(descending) println(ascending) [75, 20, 10, 5, -6] [-6, 5, 10, 20, 75] The statement itself clearly defines that when string1 is greater than string 2 return true otherwise false hence return statement is omitted here. Known Type Closures Consider the addition of two numbers. We know that addition will return the integer datatype. Hence known type closures are declared as let sub = {(no1: Int, no2: Int) -> Int in return no1 - no2 let digits = sub(10, 20) println(digits) -10 Declaring Shorthand Argument Names as Closures Swift automatically provides shorthand argument names to inline closures, which can be used to refer to the values of the closure's arguments by the names 0, 1, $2, and so on. var shorthand: (String, String) -> String shorthand = { $1 println(shorthand("100", "200")) Here, 0and1 refer to the closure's first and second String arguments. 200 Swift facilitates the user to represent Inline closures as shorthand argument names by representing 0, 1, 2 n. Closures argument list is omitted in definition section when we represent shorthand argument names inside closure expressions. Based on the function type the shorthand argument names will be derived. Since the shorthand argument is defined in expression body the 'in' keyword is omitted.

Closures as Operator Functions Swift provides an easy way to access the members by just providing operator functions as closures. In the previous examples keyword 'Bool' is used to return either 'true' when the strings are equal otherwise it returns 'false'. The expression is even made simpler by operator function in closure as let numb = [98, -20, -30, 42, 18, 35] var sortednumbers = numb.sorted({ (left: Int, right: Int) -> Bool in return left < right ) let asc = numb.sorted(<) println(asc) [-30, -20, 18, 35, 42, 98] Closures as Trailers Passing the function's final argument to a closure expression is declared with the help of 'Trailing Closures'. It is written outside the function with {. Its usage is needed when it is not possible to write the function inline on a single line. reversed = sorted(names) { $0 > $1 where {0 > 1 are represented as trailing closures declared outside names. import Foundation var letters = ["North", "East", "West", "South"] let twoletters = letters.map({ (state: String) -> String in return state.substringtoindex(advance(state.startindex, 2)).uppercaseString ) let stletters = letters.map() { $0.substringToIndex(advance($0.startIndex, 2)).uppercaseString println(stletters) [NO, EA, WE, SO] Capturing Values and Reference Types In Swift capturing constants and variables values are done with the help of closures. It further refers and modify the values for those constants and variables inside the closure body even though the variables no longer exists. Capturing constant and variable values is achieved by using nested function by writing function with in the body of other function. A nested function captures Outer function arguments. Capture constants and variables defined within the Outer function. In Swift when the constant or variable is declared inside a function, reference to that variables are also automatically created by the closure. It also provides the facility to refer more than two variables as the same closure as follows let decrem = calcdecrement(fordecrement: 18)

Here onedecrement and Decrement variables will both point the same memory block as closure reference. func calcdecrement(fordecrement total: Int) -> () -> Int { var overalldecrement = 100 func decrementer() -> Int { overalldecrement -= total println(overalldecrement) return overalldecrement return decrementer let decrem = calcdecrement(fordecrement: 18) 82 64 46 When each and every time the outer function calcdecrement is called it invokes the decrementer function and decrements the value by 18 and returns the result with the help of outer function calcdecrement. Here calcdecrement acts as a closure. Eventhough the function decrementer does not have any arguments closure by default refers to variables 'overalldecrement' and 'total' by capturing its existing values. The copy of the values for the specified variables are stored with the new decrementer function. Swift handles memory management functions by allocating and deallocating memory spaces when the variables are not in use. Loading [MathJax]/jax/output/HTML-CSS/jax.js