Tcl – Built-in Functions

Tcl – Built-in Functions ”; Previous Next Tcl provides a number of built-in functions (procedures) for various operations. This includes − Functions for list handling. Functions for string handling. Functions for array handling. Functions for dictionary handling. Functions for File I/O handling. Functions for creating namespaces and packages. Functions for Math operations. Functions for System operations. Each of the above except for math and system functions are covered in earlier chapters. Math and system built-in functions are explained below. Math Functions The math functions available in Tcl are listed in the following table − Sr.No. Method & Description 1 abs arg Calculates the absolute value of arg. 2 acos arg Calculates the arccosine of arg. 3 asin arg Calculates the arcsine of arg. 4 atan arg Calculates the arctangent of arg. 5 atan2 y x Calculates the arctangent of the quotient of its arguments(y/x). 6 ceil arg Calculates the smallest integer greater than or equal to a number. 7 cos arg Calculates the cosine of arg. 8 cosh arg Calculates the hyperbolic cosine of arg. 9 double arg Calculates if arg is a floating-point value, returns arg, otherwise converts arg to floating-point and returns the converted value. 10 exp arg Calculates an exponential function (e raised to the power of arg). 11 floor arg Calculates the largest integer less than or equal to arg. 12 fmod x y Calculates the floating-point remainder of the division of x by y. If y is 0, an error is returned. 13 hypot x y Calculates the length of the hypotenuse of a right-angled triangle sqrt(x*x+y*y). 14 int arg Calculates if arg is an integer value of the same width as the machine word, returns arg, otherwise converts arg to an integer. 15 log arg Calculates the natural logarithm of arg. 16 log10 arg Calculates the base 10 logarithm of arg. 17 pow x y Calculates the value of x raised to the power y. If x is negative, y must be an integer value. 18 rand Calculates a pseudo-random number between 0 and 1. 19 round arg Calculates the value of arg rounded to the nearest integer. 20 sin arg Calculates the sine of arg. 21 sinh arg Calculates the hyperbolic sine of arg. 22 sqrt arg Calculates the square root of arg. arg must be positive. 23 srand arg Calculates a pseudo-random number between 0 and 1. The arg, which must be an integer, is used to reset the seed for the random number generator of rand. 24 tan arg Calculates the tangent of arg. 25 tanh arg Calculates the hyperbolic tangent of arg. 26 wide arg Calculates integer value at least 64-bits wide (by sign-extension if arg is a 32-bit number) for arg if it is not one already. Some examples using math functions are given below − Live Demo #!/usr/bin/tclsh namespace import ::tcl::mathfunc::* puts [tan 10] puts [pow 10 2] puts [ceil 10.34] puts [hypot 10 20] puts [srand 45] puts [log 10] puts [srand 45] When the above code is executed, it produces the following result − 0.6483608274590866 100.0 11.0 22.360679774997898 0.0003521866166741525 2.302585092994046 0.0003521866166741525 System Functions The important system functions in Tcl includes, clock − seconds function, which returns current time in seconds. clock − format function, which formats the seconds into date and time. clock − scan function, which scans the input string and converts it into seconds. open − function, which is used to open a file. exec − function, which is used to execute a system command. close − function, which is used to close a file. Some examples for the above functions are listed below − #!/usr/bin/tclsh #get seconds set currentTime [clock seconds] puts $currentTime #get format puts “The time is: [clock format $currentTime -format %H:%M:%S]” puts “The date is: [clock format $currentTime -format %D]” set date “Jun 15, 2014″ puts [clock scan $date -format {%b %d, %Y}] puts [exec ls] puts [exec dir] set a [open input.txt] puts [read $a]; puts $a close $a When the above code is executed, it produces the following result − 1402819756 The time is: 03:09:16 The date is: 06/15/2014 1402808400 input.txt main.tcl input.txt main.tcl This is the file you can use to provide input to your program and later on open it inside your program to process the input. file3 The following table provides the list strings that can be used to format the date and time. Sr.No. Format & Description 1 %a Day in short form, eg:Sun. 2 %A Day in full form eg:Sunday. 3 %b Month in short form. 4 %B Month in full form. 5 %d Day of month. 6 %j Julian day of year. 7 %m Month in number. 8 %y Year in two digits. 9 %Y Year in four digits. 10 %H Hour in 24 hour clock. 11 %I Hour in 12 hour clock. 12 %M Minutes. 13 %S Seconds. 14 %p AM or PM. 15 %D Date in number, mm /dd/yy. 16 %r Time in 12 hour clock. 17 %R Time in 24 hour clock without seconds. 18 %T Time in 24 hour clock with seconds. 19 %Z Time Zone Name like GMT, IST, EST and so on. Print Page Previous Next Advertisements ”;

Solidity – Abstract Contracts

Solidity – Abstract Contracts ”; Previous Next Abstract Contract is one which contains at least one function without any implementation. Such a contract is used as a base contract. Generally an abstract contract contains both implemented as well as abstract functions. Derived contract will implement the abstract function and use the existing functions as and when required. In case, a derived contract is not implementing the abstract function then this derived contract will be marked as abstract. Example Try the following code to understand how the abstract contracts works in Solidity. pragma solidity ^0.5.0; contract Calculator { function getResult() public view returns(uint); } contract Test is Calculator { function getResult() public view returns(uint) { uint a = 1; uint b = 2; uint result = a + b; return result; } } Run the above program using steps provided in Solidity First Application chapter. Output 0: uint256: 3 Print Page Previous Next Advertisements ”;

Swift – Quick Guide

Swift – Quick Guide ”; Previous Next Swift – Overview Swift 4 is a new programming language developed by Apple Inc for iOS and OS X development. Swift 4 adopts the best of C and Objective-C, without the constraints of C compatibility. Swift 4 makes use of safe programming patterns. Swift 4 provides modern programming features. Swift 4 provides Objective-C like syntax. Swift 4 is a fantastic way to write iOS and OS X apps. Swift 4 provides seamless access to existing Cocoa frameworks. Swift 4 unifies the procedural and object-oriented portions of the language. Swift 4 does not need a separate library import to support functionalities like input/output or string handling. Swift 4 uses the same runtime as the existing Obj-C system on Mac OS and iOS, which enables Swift 4 programs to run on many existing iOS 6 and OS X 10.8 platforms. Swift 4 comes with playground feature where Swift 4 programmers can write their code and execute it to see the results immediately. The first public release of Swift was released in 2010. It took Chris Lattner almost 14 years to come up with the first official version, and later, it was supported by many other contributors. Swift 4 has been included in Xcode 6 beta. Swift designers took ideas from various other popular languages such as Objective-C, Rust, Haskell, Ruby, Python, C#, and CLU. Swift – Environment Local Environment Setup Swift 4 provides a Playground platform for learning purpose and we are going to setup the same. You need xCode software to start your Swift 4 coding in Playground. Once you are comfortable with the concepts of Swift 4, you can use xCode IDE for iOS/OS x application development. To start with, we consider you already have an account at Apple Developer website. Once you are logged in, go to the following link − Download for Apple Developers This will list down a number of software available as follows − Now select xCode and download it by clicking on the given link near to disc image. After downloading the dmg file, you can install it by simply double-clicking on it and following the given instructions. Finally, follow the given instructions and drop xCode icon into the Application folder. Now you have xCode installed on your machine. Next, open Xcode from the Application folder and proceed after accepting the terms and conditions. If everything is fine, you will get the following screen − Select Get started with a playground option and enter a name for playground and select iOS as platform. Finally, you will get the Playground window as follows − Following is the code taken from the default Swift 4 Playground Window. import UIKit var str = “Hello, playground” If you create the same program for OS X program, then it will include import Cocoa and the program will look like as follows − import Cocoa var str = “Hello, playground” When the above program gets loaded, it should display the following result in Playground result area (Right Hand Side). Hello, playground Congratulations, you have your Swift 4 programming environment ready and you can proceed with your learning vehicle “Tutorials Point”. Swift – Basic Syntax We have already seen a piece of Swift 4 program while setting up the environment. Let”s start once again with the following Hello, World! program created for OS X playground, which includes import Cocoa as shown below − /* My first program in Swift 4 */ var myString = “Hello, World!” print(myString) If you create the same program for iOS playground, then it will include import UIKit and the program will look as follows − import UIKit var myString = “Hello, World!” print(myString) When we run the above program using an appropriate playground, we will get the following result − Hello, World! Let us now see the basic structure of a Swift 4 program, so that it will be easy for you to understand the basic building blocks of the Swift 4 programming language. Import in Swift 4 You can use the import statement to import any Objective-C framework (or C library) directly into your Swift 4 program. For example, the above import cocoa statement makes all Cocoa libraries, APIs, and runtimes that form the development layer for all of OS X, available in Swift 4. Cocoa is implemented in Objective-C, which is a superset of C, so it is easy to mix C and even C++ into your Swift 4 applications. Tokens in Swift 4 A Swift 4 program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal, or a symbol. For example, the following Swift 4 statement consists of three tokens − print(“test!”) The individual tokens are: print(“test!”) Comments Comments are like helping texts in your Swift 4 program. They are ignored by the compiler. Multi-line comments start with /* and terminate with the characters */ as shown below − /* My first program in Swift 4 */ Multi-line comments can be nested in Swift 4. Following is a valid comment in Swift 4 − /* My first program in Swift 4 is Hello, World! /* Where as second program is Hello, Swift 4! */ */ Single-line comments are written using // at the beginning of the comment. // My first program in Swift 4 Semicolons Swift 4 does not require you to type a semicolon (;) after each statement in your code, though it’s optional; and if you use a semicolon, then the compiler does not complain about it. However, if you are using multiple statements in the same line, then it is required to use a semicolon as a delimiter, otherwise the compiler will raise a syntax error. You can write the above Hello, World! program as follows − /* My first program in Swift 4 */ var myString = “Hello, World!”; print(myString) Identifiers A Swift 4 identifier is a name used to identify a variable, function, or any other userdefined item. An

Swift – Compile Online

Compile Swift Online ”; Previous Next You really do not need to set up your own environment to start learning Swift programming. Reason is very simple, we already have set up Swift environment online, so that you can execute all the available examples online at the same time when you are doing your theory work. This gives you confidence in what you are reading and to check the result with different options. Feel free to modify any example and execute it online. Try following example using Live Demo option available at the top right corner of the below sample code box: Live Demo let constA = 42 print(constA) let constB:Float = 3.14159 print(constB) For most of the examples given in this tutorial, you will find Live Demo option, so just make use of it and enjoy your learning. Print Page Previous Next Advertisements ”;

Tcl – Commands

Tcl – Commands ”; Previous Next As you know, Tcl is a Tool command language, commands are the most vital part of the language. Tcl commands are built in-to the language with each having its own predefined function. These commands form the reserved words of the language and cannot be used for other variable naming. The advantage with these Tcl commands is that, you can define your own implementation for any of these commands to replace the original built-in functionality. Each of the Tcl commands validates the input and it reduces the work of the interpreter. Tcl command is actually a list of words, with the first word representing the command to be executed. The next words represent the arguments. In order to group the words into a single argument, we enclose multiple words with “” or {}. The syntax of Tcl command is as follows − commandName argument1 argument2 … argumentN Let”s see a simple example of Tcl command − Live Demo #!/usr/bin/tclsh puts “Hello, world!” When the above code is executed, it produces the following result − Hello, world! In the above code, ‘puts’ is the Tcl command and “Hello World” is the argument1. As said before, we have used “” to group two words. Let”s see another example of Tcl command with two arguments − Live Demo #!/usr/bin/tclsh puts stdout “Hello, world!” When the above code is executed, it produces the following result − Hello, world! In the above code, ‘puts’ is the Tcl command, ‘stdout’ is argument1, and “Hello World” is argument2. Here, stdout makes the program to print in the standard output device. Command Substitution In command substitutions, square brackets are used to evaluate the scripts inside the square brackets. A simple example to add two numbers is shown below − Live Demo #!/usr/bin/tclsh puts [expr 1 + 6 + 9] When the above code is executed, it produces following result − 16 Variable Substitution In variable substitutions, $ is used before the variable name and this returns the contents of the variable. A simple example to set a value to a variable and print it is shown below. Live Demo #!/usr/bin/tclsh set a 3 puts $a When the above code is executed, it produces the following result − 3 Backslash Substitution These are commonly called escape sequences; with each backslash, followed by a letter having its own meaning. A simple example for newline substitution is shown below − Live Demo #!/usr/bin/tclsh puts “HellonWorld” When the above code is executed, it produces the following result − Hello World Print Page Previous Next Advertisements ”;

Scala Collections – ListMap

Scala Collections – ListMap ”; Previous Next Scala map is a collection of key/value pairs. Any value can be retrieved based on its key. Keys are unique in the Map, but values need not be unique. ListMap implements immutable map and uses list to implement the same. It is used with small number of elements. Declaring ListMap Variables The following is the syntax for declaring an ListMap variable. Syntax val colors = ListMap(“red” -> “#FF0000”, “azure” -> “#F0FFFF”, “peru” -> “#CD853F”) Here, colors is declared as an hash-map of Strings, Int which has three key-value pairs. Values can be added by using commands like the following − Command var myMap1: ListMap[Char, Int] = colors + (“black” -> “#000000”); Processing ListMap Below is an example program of showing how to create, initialize and process ListMap − Example import scala.collection.immutable.ListMap object Demo { def main(args: Array[String]) = { var myMap: ListMap[String,String] = ListMap( “red” -> “#FF0000”, “azure” -> “#F0FFFF”, “peru” -> “#CD853F” ); // Add an element var myMap1: ListMap[String,String] = myMap + (“white” -> “#FFFFFF”); // Print key values myMap.keys.foreach{ i => print( “Key = ” + i ) println(” Value = ” + myMap(i) ) } if( myMap.contains( “red” )) { println(“Red key exists with value :” + myMap(“red”)) } else { println(“Red key does not exist”) } if( myMap.contains( “maroon” )) { println(“Maroon key exists with value :” + myMap(“maroon”)) } else { println(“Maroon key does not exist”) } //removing element var myMap2: ListMap[String,String] = myMap – (“white”); // Create empty map var myMap3: ListMap[String,String] = ListMap.empty[String, String]; println(myMap1); println(myMap2); println(myMap3); } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output Key = red Value = #FF0000 Key = azure Value = #F0FFFF Key = peru Value = #CD853F Red key exists with value :#FF0000 Maroon key does not exist ListMap(red -> #FF0000, azure -> #F0FFFF, peru -> #CD853F, white -> #FFFFFF) ListMap(red -> #FF0000, azure -> #F0FFFF, peru -> #CD853F) ListMap() Print Page Previous Next Advertisements ”;

Tk – Fonts

Tk – Fonts ”; Previous Next There are a number of widgets that supports displaying text. Most of these provides the option of font attribute. The syntax for creating a font is shown below − font create fontName options Options The options available for the font create are listed below in the following table − Sr.No. Syntax & Description 1 -family familyName The name of font family. 2 -size number The size of font. 3 -weight level The weight for font. A simple example for a font creation is shown below − #!/usr/bin/wish font create myFont -family Helvetica -size 18 -weight bold pack [label .myLabel -font myFont -text “Hello World”] When we run the above program, we will get the following output − To get all the fonts available, we can use the following command − #!/usr/bin/wish puts [font families] When we run the above command, we will get the following output − {Abadi MT Condensed Extra Bold} {Abadi MT Condensed Light} {Al Bayan} {Al Nile} {Al Tarikh} {American Typewriter} {Andale Mono} Arial {Arial Black} {Arial Hebrew} {Arial Narrow} {Arial Rounded MT Bold} {Arial Unicode MS} Athelas Avenir {Avenir Next} {Avenir Next Condensed} Ayuthaya Baghdad {Bangla MN} {Bangla Sangam MN} {Baoli SC} Baskerville {Baskerville Old Face} Batang {Bauhaus 93} Beirut {Bell MT} {Bernard MT Condensed} BiauKai {Big Caslon} {Book Antiqua} {Bookman Old Style} {Bookshelf Symbol 7} Braggadocio {Britannic Bold} {Brush Script MT} Calibri {Calisto MT} Cambria {Cambria Math} Candara Century {Century Gothic} {Century Schoolbook} Chalkboard {Chalkboard SE} Chalkduster {Charcoal CY} Charter Cochin {Colonna MT} {Comic Sans MS} Consolas Constantia {Cooper Black} Copperplate {Copperplate Gothic Bold} {Copperplate Gothic Light} Corbel {Corsiva Hebrew} Courier {Courier New} {Curlz MT} Damascus {DecoType Naskh} Desdemona {Devanagari MT} {Devanagari Sangam MN} Didot {DIN Alternate} {DIN Condensed} {Diwan Kufi} {Diwan Thuluth} {Edwardian Script ITC} {Engravers MT} {Euphemia UCAS} Eurostile Farah Farisi {Footlight MT Light} {Franklin Gothic Book} {Franklin Gothic Medium} Futura Gabriola Garamond {GB18030 Bitmap} {Geeza Pro} Geneva {Geneva CY} Georgia {Gill Sans} {Gill Sans MT} {Gloucester MT Extra Condensed} {Goudy Old Style} {Gujarati MT} {Gujarati Sangam MN} Gulim GungSeo {Gurmukhi MN} {Gurmukhi MT} {Gurmukhi Sangam MN} Haettenschweiler {Hannotate SC} {Hannotate TC} {HanziPen SC} {HanziPen TC} Harrington HeadLineA Hei {Heiti SC} {Heiti TC} Helvetica {Helvetica CY} {Helvetica Neue} Herculanum {Hiragino Kaku Gothic Pro} {Hiragino Kaku Gothic ProN} {Hiragino Kaku Gothic Std} {Hiragino Kaku Gothic StdN} {Hiragino Maru Gothic Pro} {Hiragino Maru Gothic ProN} {Hiragino Mincho Pro} {Hiragino Mincho ProN} {Hiragino Sans GB} {Hoefler Text} Impact {Imprint MT Shadow} InaiMathi {Iowan Old Style} Kai Kailasa {Kaiti SC} {Kaiti TC} {Kannada MN} {Kannada Sangam MN} Kefa {Khmer MN} {Khmer Sangam MN} {Kino MT} Kokonor Krungthep KufiStandardGK {Lantinghei SC} {Lantinghei TC} {Lao MN} {Lao Sangam MN} {Libian SC} {LiHei Pro} {LiSong Pro} {Lucida Blackletter} {Lucida Bright} {Lucida Calligraphy} {Lucida Console} {Lucida Fax} {Lucida Grande} {Lucida Handwriting} {Lucida Sans} {Lucida Sans Typewriter} {Lucida Sans Unicode} {Malayalam MN} {Malayalam Sangam MN} Marion {Marker Felt} Marlett {Matura MT Script Capitals} Meiryo Menlo {Microsoft Sans Serif} Mishafi Mistral {Modern No. 20} Monaco {MS Gothic} {MS Mincho} {MS PGothic} {MS PMincho} {MS Reference Sans Serif} {MS Reference Specialty} Mshtakan {MT Extra} Muna {Myanmar MN} {Myanmar Sangam MN} Nadeem {Nanum Brush Script} {Nanum Gothic} {Nanum Myeongjo} {Nanum Pen Script} {New Peninim MT} {News Gothic MT} Noteworthy Onyx Optima {Oriya MN} {Oriya Sangam MN} Osaka Palatino {Palatino Linotype} Papyrus PCMyungjo Perpetua {Perpetua Titling MT} PilGi {Plantagenet Cherokee} Playbill PMingLiU {PT Mono} {PT Sans} {PT Sans Caption} {PT Sans Narrow} {PT Serif} {PT Serif Caption} Raanana Rockwell {Rockwell Extra Bold} Sana Sathu {Savoye LET} Seravek Silom SimSun {Sinhala MN} {Sinhala Sangam MN} Skia {Snell Roundhand} {Songti SC} {Songti TC} Stencil STFangsong STHeiti STIXGeneral STIXIntegralsD STIXIntegralsSm STIXIntegralsUp STIXIntegralsUpD STIXIntegralsUpSm STIXNonUnicode STIXSizeFiveSym STIXSizeFourSym STIXSizeOneSym STIXSizeThreeSym STIXSizeTwoSym STIXVariants STKaiti STSong Superclarendon Symbol Tahoma {Tamil MN} {Tamil Sangam MN} TeamViewer8 {Telugu MN} {Telugu Sangam MN} Thonburi Times {Times New Roman} {Trebuchet MS} {Tw Cen MT} Verdana Waseem {Wawati SC} {Wawati TC} Webdings {Weibei SC} {Weibei TC} {Wide Latin} Wingdings {Wingdings 2} {Wingdings 3} {Xingkai SC} {Yuanti SC} YuGothic YuMincho {Yuppy SC} {Yuppy TC} {Zapf Dingbats} Zapfino {Apple Braille} {Apple Chancery} {Apple Color Emoji} {Apple LiGothic} {Apple LiSung} {Apple SD Gothic Neo} {Apple Symbols} AppleGothic AppleMyungjo {Monotype Corsiva} {Monotype Sorts} Print Page Previous Next Advertisements ”;

Swift – Access Control

Swift – Access Control ”; Previous Next Access controls are used to restrict access to the specified part of the code or module. It prevents unauthorized access and implements encapsulation. The access control mechanism controls the access of the methods and properties of classes, structures and enumerations. Constants, variables and functions in a protocol are restricted and allowed access as global and local through access control. Access control applied to properties, types and functions can be referred to as ”entities”. The access control model is based on modules and source files. The module is defined as a single code distribution unit and can be imported using the keyword ”import”. A source file is defined as a single source code file within a module to access multiple types and functions. Access Levels in Swift Swift supports the following access levels and they are: Access Levels Definition Open It is the least restrictive access level. It is applicable only to classes and class memebers. It allows class and class members to be subclassed or overrridden in another module. Public It allows entities to be access from any source file within the same or different module. Internal It allows entities to be used within any source file from their defining module, but not outside of that module. Private It restricts the use of an entity to its own defining source file. It hides the implementation details of a specific code functionality. It is the most restrctive access level. File-Private It also restricts the use of an entity to its own defining source file. It hides the implementation details of a specific code functionality when those details are used inside the entire file. Rules of using Access levels Following are some rules that must be known by the developers while using access level − The public variable can not be defined as internal, file-private or private. The function does not have a higher access level than its parameter and return type. The default access level for all the entities is internal. The default access level for single-target apps is internal. The default access level for frameworks is either open or public. Syntax public class SomePublicClass {} internal class SomeInternalClass {} private class SomePrivateClass {} public var somePublicVariable = 0 internal let someInternalConstant = 0 private func somePrivateFunction() {} Access Control for Function types Some functions may have arguments declared inside the function without any return values. The following program declares a and b as arguments to the sum() function. Inside the function itself, the values for arguments a and b are passed by invoking the function call sum() and its values are printed thereby eliminating return values. To make the function”s return type as private, declare the function”s overall access level with the private modifier. Example Swift program to demonstrate access control for function types. // Private function private func sum(a: Int, b: Int) { let a = a + b let b = a – b print(a, b) } // Calling the function sum(a: 20, b: 10) sum(a: 40, b: 10) sum(a: 24, b: 6) Output It will produce the following output − 30 20 50 40 30 24 Access Control for Enumeration types The enumeration in Swift automatically receives the same access level for individual cases of an enumeration. Consider for example accessing the student name and marks secured in three subjects enumeration name is declared as a student and the members present in the enum class are a name that belongs to string datatype, marks are represented as mark1, mark2 and mark3 of datatype Integer. To access either the student name or marks they have scored. Now, the switch case will print the student”s name if that case block is executed otherwise it will print the marks secured by the student. Example Swift program to demonstrate access control for enumeration types. // Enumeration public enum Student { case Name(String) case Mark(Int, Int, Int) } var studDetails = Student.Name(“Swift”) var studMarks = Student.Mark(98, 97, 95) switch studDetails { case .Name(let studName): print(“Student name is: (studName).”) case .Mark(let Mark1, let Mark2, let Mark3): print(“Student Marks are: (Mark1), (Mark2), (Mark3).”) } Output It will produce the following output − Student name is: Swift. Access Control for SubClasses Swift allows the user to subclass any class that can be accessed in the current access context. A subclass cannot have a higher access level than its superclass. The user is restricted from writing a public subclass of an internal superclass. Example Swift program to demonstrate access control for subclasses. // Class public class Cricket { internal func display() { print(“Welcome to Swift Super Class”) } } // Subclass internal class Tennis: Cricket { override internal func display() { print(“Welcome to Swift Sub Class”) } } let cricketInstance = Cricket() cricketInstance.display() let tennisInstance = Tennis() tennisInstance.display() Output It will produce the following output − Welcome to Swift Super Class Welcome to Swift Sub Class Access Control for Constants, variables, properties and subscripts We are allowed to control the visibility of the constants, variables, properties and subscripts with the help of access controls. When a constant, variable, property or subscript uses private type, then that constant, variable, property, or subscript must be marked as private. And we are not valid to write a public property with a private type. Similarly, a subscript cannot be more public than its return type. Example private var privateInstance = SomePrivateClass() Access Control for Getters and

Swift – Error handling

Swift – Error Handling ”; Previous Next Error handling is a process of managing and responding to unexpected situations that occur during the execution of the program. Errors may occur due to various reasons like hardware issues, logical mistakes, unexpected user input, etc. Swift provides good support for catching, throwing, and manipulating recoverable errors during runtime. The main goals of error handling are: Detect Errors − Identify where and what type of error occurs in the program. Reporting Errors − Report the details of the error to the developer or end-user. Handling Errors − Take proper action against the occurred error which may include providing an error message, logging information for debugging or implementing strategies for recovery. Now in this article, we will discuss how errors are represented, propogated, and handled by the Swift. How an error is represented in Swift? In Swift, an error is represented by using the type that conforms to the Error protocol. The Error protocol is empty, which means it does not have any specific methods and properties to implement instead it allows us to create our own custom error types by defining a new type that conforms to the Error protocol. The best way to represent errors is enumeration. It grouped all the related error conditions with associated values and information about the error’s behaviour. Example The following Swift example will show how to represent an error. enum MyNewError: Error { case invalidInput case fileNotFound case networkError // Add more cases if you require } Throwing Error in Swift In Swift, throwing an error means when a function or a method detects something unexpected that prevents it from executing in the normal way, then it throws an error that tells that something unexpected has occurred. It is further helpful in handling the error. We can throw errors with the help of a throw statement. Syntax Following is the syntax for throwing an error − throw enumerationName.error Example Following Swift”s example we show how to throw an error. throw MyNewError.fileNotFound Propagating Errors Using Throwing Functions We can propagate errors from the throwing function. The throwing function is a function marked with the throw keyword. In Swift, functions, methods, or initializers can throw errors. When a function, method, or initializer encounters an error, then they can use the throws keyword in their declaration part after the parameter and before the return arrow(->). Only the throwing function is allowed to propagate errors. If an error occurs inside the non-throwing function, then that error must be handled inside that function. Syntax Following is the syntax for the throwing function − func functionName(parameterList) throws -> ReturnType Example The following Swift program will show how to throw an error using the throwing function. enum MyNewError: Error { case invalidInput case fileNotFound case networkError } // Throwing Function func processData(_ enterValue: String) throws { guard !enterValue.isEmpty else { throw MyNewError.invalidInput } } // Handling errors do { // Calling throwing function try processData(“”) print(“Successful”) } catch MyNewError.invalidInput { print(“Invalid input”) } catch { print(“Unexpected error occurred: (error)”) } Output It will produce the following output − Invalid input Disabling Error Propagation We can disable error propagation with the help of try! Keyword. It is helpful when we are confident the error does not occur at runtime and can simplify the error handling code. However, be careful while using try! Keyword if an error occurs, then our program will crash at runtime. Example Swift program to demonstrate how to disable error propagation. // Set of errors enum myNewError: Error { case divisionByZero case invalidInput } // Throwing function func divideNum(_ dividend: Int, by divisor: Int) throws -> Int { guard divisor != 0 else { throw myNewError.divisionByZero } return dividend / divisor } // Here we”re sure that the divisor is not zero, // so we use try! to disable error propagation. let output = try! divideNum(10, by: 2) print(output) Output It will produce the following output − 5 Handling Errors Using Do-Catch In Swift, we can handle errors with the help of a do-catch statement. It makes our code more robust and allows us to provide specific error-handling logic for various errors. In the do-catch statement, the do block contains the code that might throw an error and the catch block handles the specific error that occurs in the do block. Not all the errors thrown by the do clause are handled by the catch clause. If none of the catch clauses handle the occurred error, then that error will propagate to the surrounding scope and the surrounding scope will handle the propagated error. If the error propagated to the top-level scope without handling then we will get a runtime error. In the non-throwing functions, the errors are handled by the enclosed do-catch statement whereas in throwing functions the errors are handled by the enclosed do-catch statement or the caller. Syntax Following is the syntax of the do-catch statement − do { try<expression> } catch <pattern1>{ // statement } catch <pattern2>{ // statement } catch <pattern3>, <pattern4> where <condition>{ // statement } catch { //statement // catch clause without pattern can match any error } Example Swift program to demonstrate how to handle errors using do-catch blocks. // Set of errors enum myNewError: Error { case divisionByZero case invalidInput } // Throwing function func divideNum(_ dividend: Int, by divisor: Int) throws -> Int { guard divisor != 0 else { throw myNewError.divisionByZero } return dividend / divisor } // Handling error using do-catch statement do { let result = try divideNum(10, by:

Swift – Singleton class

Swift – Singleton Class ”; Previous Next A Singleton Class is a special class which have only one object and will make sure that your application or program uses that object. If you try to create another variable of singleton class you will get an error. Singleton class is easy to use but it has a major drawback which is global access, which means you can access singleton class globally by sharing the instance of the class. Which makes it hard to maintain, can lead to concurrency issues, etc. So to avoid excess use of singleton object we use dependency injection. Dependency injection passes the singleton object to the object where it is required. If a class depends upon the singleton and they are present in different contexts, then you have to import a singleton into that context without importing the class cannot access the singleton. Syntax Following is the syntax of the Singleton Class − class Name{ // body } Creating and Accessing Singleton Class We can create a singleton class just like the normal class using the “class” keyword but with some different rules and they are − A singleton class should have a private initializer. A singleton class should have a static-type object. Private Initializer This private initializer prevents the object creation from outside the class. If you try to create an object outside the class you will get an error. To create a private initializer we will use a “private” keyword. Syntax Following is the syntax for private initializer − private init(){} Example Swift program to create a singleton class with a private initializer. import Foundation // Outer class class SingletonClass{ // Creating a private initializer private init(){} func show(){ print(“Hello”) } } // Creating object outside the class // We will get an error let myObject = SingletonClass() myObject.show() Output It will produce the following output − main.swift:16:16: error: ”SingletonClass” initializer is inaccessible due to ”private” protection level let myObject = SingletonClass() Here the private protection level prevents us from creating an object outside the class. So to overcome this error we have to create an object inside the class. Static Object If we have a static object inside the single class we can easily access the object by using the class name. To create a static object we use the “Static” keyword. Syntax Following is the syntax for static objects − static let objectName = className() Following is the syntax for accessing static objects − let variableName = className.objectName Example Swift program to create a singleton class with an object. import Foundation // Singleton class class SingletonClass{ // Creating object outside the class static let myObject = SingletonClass() // Creating a private initializer private init(){} // Method func show(){ print(“Hello I am Singleton Class”) } } // Accessing the object let ob = SingletonClass.myObject // Accessing the method ob.show() Output It will produce the following output − Hello I am Singleton Class Singleton Class Normal Class It have only one instance throughout the lifetime of the program. It can have multiple instances. It does not allows you to create instances of the class. It allows you to directly create instances of the class using its initializer. You can access the instance with the help of shared properties and methods that provide global access to the object. You can directly access the instances. It is less flexible in terms of creating objects and can use tight coupling between different parts of the code. It is more flexible in terms of creating objects and can allow loose coupling between different parts of the code. Testing singleton class is difficult because of global state and dependencies. Testing normal classes is much more easier. Print Page Previous Next Advertisements ”;