archive-com.com » COM » T » TECHOTOPIA.COM

Total: 1018

Choose link from "Titles, links and description words view":

Or switch to "Titles and links view".
  • Swift 2 Flow Control - Techotopia
    a particular task needs to be repeated in a program There will however be instances where code needs to be repeated until a certain condition is met with no way of knowing in advance how many repetitions are going to be needed to meet that criteria To address this need Swift provides the while loop Essentially the while loop repeats a set of tasks until a specified condition is met The while loop syntax is defined as follows while condition Swift statements go here In the above syntax condition is an expression that will return either true or false and the Swift statements go here comment represents the code to be executed while the condition expression is true For example var myCount 0 while myCount 100 myCount In the above example the while expression will evaluate whether the myCount variable is less than 100 If it is already greater than 100 the code in the braces is skipped and the loop exits without performing any tasks eBookFrenzy com Purchase the full edition of this iOS 9 App Development Essentials book in eBook 12 99 or Print 39 99 format iOS 9 App Development Essentials Print and eBook ePub PDF Kindle edition contains 105 chapters If on the other hand myCount is not greater than 100 the code in the braces is executed and the loop returns to the while statement and repeats the evaluation of myCount This process repeats until the value of myCount is greater than 100 at which point the loop exits The do while loop It is often helpful to think of the do while loop as an inverted while loop The while loop evaluates an expression before executing the code contained in the body of the loop If the expression evaluates to false on the first check then the code is not executed The do while loop on the other hand is provided for situations where you know that the code contained in the body of the loop will always need to be executed at least once For example you may want to keep stepping through the items in an array until a specific item is found You know that you have to at least check the first item in the array to have any hope of finding the entry you need The syntax for the do while loop is as follows do Swift statements here while conditional expression In the do while example below the loop will continue until the value of a variable named i equals 0 var i 10 do i while i 0 Breaking from Loops Having created a loop it is possible that under certain conditions you might want to break out of the loop before the completion criteria have been met particularly if you have created an infinite loop One such example might involve continually checking for activity on a network socket Once activity has been detected it will most likely be necessary to break out of the monitoring loop

    Original URL path: http://www.techotopia.com/index.php/Swift_2_Flow_Control (2016-02-13)
    Open archived version from archive


  • The Swift 2 Switch Statement - Techotopia
    statements present a match to the expression A Swift switch Statement Example With the above information in mind we may now construct a simple switch statement var value 4 switch value case 0 println zero case 1 println one case 2 println two case 3 println three case 4 println four case 5 println five default println Integer out of range Combining case Statements In the above example each case had its own set of statements to execute Sometimes a number of different matches may require the same code to be executed In this case it is possible to group case matches together with a common set of statements to be executed when a match for any of the cases is found For example we can modify the switch construct in our example so that the same code is executed regardless of whether the value is 0 1 or 2 var value 1 switch value case 0 1 2 println zero one or two case 3 println three case 4 println four case 5 println five default println Integer out of range Range Matching in a switch Statement The case statements within a switch construct may also be used to implement range matching The following switch statement for example checks a temperature value for matches within three number ranges var temperature 83 switch temperature case 0 49 println Cold case 50 79 println Warm case 80 110 println Hot default println Temperature out of range Using the where statement The where statement may be used within a switch case match to add additional criteria required for a positive match The following switch statement for example checks not only for the range in which a value falls but also whether the number is odd or even var temperature 54 switch temperature

    Original URL path: http://www.techotopia.com/index.php/The_Swift_2_Switch_Statement (2016-02-13)
    Open archived version from archive

  • An Overview of Swift 2 Functions, Methods and Closures - Techotopia
    from a Function A function can return multiple result values by wrapping those results in a tuple The following function takes as a parameter a measurement value in inches The function converts this value into yards centimeters and meters returning all three results within a single tuple instance func sizeConverter length Float yards Float centimeters Float meters Float var yards length 0 0277778 var centimeters length 2 54 var meters length 0 0254 return yards centimeters meters The return type for the function indicates that the function returns a tuple containing three values named yards centimeters and meters respectively all of which are of type Float yards Float centimeters Float meters Float Having performed the conversion the function simply constructs the tuple instance and returns it Usage of this function might read as follows var lengthTuple sizeConverter 20 println lengthTuple yards println lengthTuple centimeters println lengthTuple meters Variable Numbers of Function Parameters It is not always possible to know in advance the number of parameters a function will need to accept when it is called within application code Swift handles this possibility through the use of variadic parameters Variadic parameters are declared using three periods to indicate that the function accepts zero or more parameters of a specified data type Within the body of the function the parameters are made available in the form of an array object The following function for example takes as parameters a variable number of String values and then outputs them to the console panel func displayStrings strings String for string in strings println string displayStrings one two three four Parameters as Variables All parameters accepted by a function are declared constants by default preventing changes being made to those parameter values within the function code If changes to parameters need to be made within the function body those parameters must be specifically declared as being variable within the function declaration The following function for example is passed length and width parameters in inches and converts those parameters which have been declared as variables to centimeters before calculating and returning the area value func calcuateArea var length Float var width Float Float length length 2 54 width width 2 54 return length width println calcuateArea 10 20 eBookFrenzy com Purchase the full edition of this iOS 9 App Development Essentials book in eBook 12 99 or Print 39 99 format iOS 9 App Development Essentials Print and eBook ePub PDF Kindle edition contains 105 chapters Working with In Out Parameters When the value assigned to a variable is passed through as an argument to a function and that function both declares the parameter as a variable and specifically changes that value the question arises as to whether that change is reflected in the original variable Consider the following code var myValue 10 func doubleValue var value Int Int value value return value println Before function call myValue myValue println doubleValue call returns doubleValue myValue println After function call myValue myValue The code begins by declaring a variable named myValue initialized with a value of 10 A new function is then declared which accepts a single integer parameter which is declared as being a variable Within the body of the function the value of the parameter is doubled and returned The remaining lines of code display the value of the myValue variable before and after the function call is made When executed the following output will appear in the console Before function call myValue 10 doubleValue call returns 20 After function call myValue 10 Clearly the function has made no change to the original myValue variable even though it was passed through to the function as an argument In order to make any changes made to a parameter persist after the function has returned the parameter must be declared as an in out parameter within the function declaration To see this in action modify the doubleValue function to prefix the parameter with the inout keyword as follows func doubleValue inout value Int Int value value return value Finally when calling the function the inout parameter must now be prefixed with an modifier println doubleValue call returned doubleValue myValue Having made these changes a test run of the code should now generate output clearly indicating that the function modified the value assigned to the original myValue variable Before function call myValue 10 doubleValue call returns 20 After function call myValue 20 Functions as Parameters An interesting feature of functions within Swift is that they can be treated as data types It is perfectly valid for example to assign a function to a constant or variable as illustrated in the declaration below func inchesToFeet inches Float Float return inches 0 0833333 let toFeet inchesToFeet The above code declares a new function named inchesToFeet and subsequently assigns that function to a constant named toFeet Having made this assignment a call to the function may be made using the constant name instead of the original function name var result toFeet 10 On the surface this does not seem to be a particularly compelling feature Since we could already call the function without assigning it to a constant or variable data type it does not seem that much has been gained The possibilities that this feature offers become more apparent when we consider that a function assigned to a constant or variable now has the capabilities of many other data types In particular a function can now be passed through as an argument to another function or even returned as a result from a function Before we look at what is essentially the ability to plug one function into another it is first necessary to explore the concept of function data types The data type of a function is dictated by a combination of the parameters it accepts and the type of result it returns In the above example since the function accepts a floating point parameter and returns a floating point result the function s data type conforms to the

    Original URL path: http://www.techotopia.com/index.php/An_Overview_of_Swift_2_Functions,_Methods_and_Closures (2016-02-13)
    Open archived version from archive

  • The Basics of Object Oriented Programming in Swift 2 - Techotopia
    implemented as follows class BankAccount var accountBalance Float 0 var accountNumber Int 0 func displayBalance println Number accountNumber println Current balance is accountBalance class func getMaxBalance Float return 100000 00 Declaring and Initializing a Class Instance So far all we have done is define the blueprint for our class In order to do anything with this class we need to create instances of it The first step in this process is to declare a variable to store a reference to the instance when it is created We do this as follows var account1 BankAccount BankAccount When executed an instance of our BankAccount class will have been created and will be accessible via the account1 variable Initializing and Deinitializing a Class Instance A class will often need to perform some initialization tasks at the point of creation These tasks can be implemented by placing an init method within the class In the case of the BankAccount class it would be useful to be able to initialize the account number and balance properties with values when a new class instance is created To achieve this the init method could be written in the class as follows class BankAccount var accountBalance Float 0 var accountNumber Int 0 init number Int balance Float accountNumber number accountBalance balance func displayBalance println Number accountNumber println Current balance is accountBalance When creating an instance of the class it will now be necessary to provide initialization values for the account number and balance properties as follows eBookFrenzy com Purchase the full edition of this iOS 9 App Development Essentials book in eBook 12 99 or Print 39 99 format iOS 9 App Development Essentials Print and eBook ePub PDF Kindle edition contains 105 chapters var account1 BankAccount number 12312312 balance 400 54 Conversely any cleanup tasks that need to be performed before a class instance is destroyed by the Swift runtime system can be performed by implementing the deinitializer within the class definition class BankAccount var accountBalance Float 0 var accountNumber Int 0 init number Int balance Float accountNumber number accountBalance balance deinit Perform any necessary clean up here func displayBalance println Number accountNumber println Current balance is accountBalance Calling Methods and Accessing Properties Now is probably a good time to recap what we have done so far in this chapter We have now created a new Swift class named BankAccount Within this new class we declared some properties to contain the bank account number and current balance together with an initializer and a method to display the current balance information In the preceding section we covered the steps necessary to create and initialize an instance of our new class The next step is to learn how to call the instance methods and access the properties we built into our class This is most easily achieved using dot notation Dot notation involves accessing an instance variable or calling an instance method by specifying a class instance followed by a dot followed in turn by the name of the

    Original URL path: http://www.techotopia.com/index.php/The_Basics_of_Object_Oriented_Programming_in_Swift_2 (2016-02-13)
    Open archived version from archive

  • An Introduction to Swift Subclassing and Extensions - Techotopia
    haven t really achieved anything unless we actually take steps to extend the class Extending the Functionality of a Subclass So far we have been able to create a subclass that contains all the functionality of the parent class In order for this exercise to make sense however we now need to extend the subclass so that it has the features we need to make it useful for storing savings account information To do this we simply add the properties and methods that provide the new functionality just as we would for any other class we might wish to create class SavingsAccount BankAccount var interestRate Float 0 0 func calculateInterest Float return interestRate accountBalance Overriding Inherited Methods When using inheritance it is not unusual to find a method in the parent class that almost does what you need but requires modification to provide the precise functionality you require That being said it is also possible you ll inherit a method with a name that describes exactly what you want to do but it actually does not come close to doing what you need One option in this scenario would be to ignore the inherited method and write a new method with an entirely new name A better option is to override the inherited method and write a new version of it in the subclass eBookFrenzy com Purchase the full edition of this iOS 9 App Development Essentials book in eBook 12 99 or Print 39 99 format iOS 9 App Development Essentials Print and eBook ePub PDF Kindle edition contains 105 chapters Before proceeding with an example there are two rules that must be obeyed when overriding a method Firstly the overriding method in the subclass must take exactly the same number and type of parameters as the overridden method in the parent class Secondly the new method must have the same return type as the parent method In our BankAccount class we have a method named displayBalance that displays the bank account number and current balance held by an instance of the class In our SavingsAccount subclass we might also want to output the current interest rate assigned to the account To achieve this we simply declare a new version of the displayBalance method in our SavingsAccount subclass prefixed with the override keyword class SavingsAccount BankAccount var interestRate Float func calculateInterest Float return interestRate accountBalance override func displayBalance print Number accountNumber print Current balance is accountBalance print Prevailing interest rate is interestRate It is also possible to make a call to the overridden method in the super class from within a subclass The displayBalance method of the super class could for example be called to display the account number and balance before the interest rate is displayed thereby eliminating further code duplication override func displayBalance super displayBalance print Prevailing interest rate is interestRate Initializing the Subclass As the SavingsAccount class currently stands it inherits the init initializer method from the parent BankAccount class which was implemented as follows init

    Original URL path: http://www.techotopia.com/index.php/An_Introduction_to_Swift_Subclassing_and_Extensions (2016-02-13)
    Open archived version from archive

  • Working with Array and Dictionary Collections in Swift 2 - Techotopia
    in looping syntax The following code for example iterates through all of the items in a String array and outputs each item to the console panel eBookFrenzy com Purchase the full edition of this iOS 9 App Development Essentials book in eBook 12 99 or Print 39 99 format iOS 9 App Development Essentials Print and eBook ePub PDF Kindle edition contains 105 chapters var treeArray Pine Oak Yew Maple Birch Myrtle for tree in treeArray print tree Upon execution the following output would appear in the console Pine Oak Yew Maple Birch Myrtle Creating Mixed Type Arrays A mixed type array is an array that can contain elements of different class types Clearly an array that is either declared or inferred as being of type String cannot subsequently be used to contain non String class object instances Interesting possibilities arise however when taking into consideration that Swift includes the AnyObject type AnyObject is a special type in Swift that can be used to reference an object of a non specific class type It follows therefore that an array declared as containing AnyObjects can be used to store elements of mixed types The following code for example declares and initializes an array containing a mixture of String Int and Double elements let mixedArray AnyObject A String 432 34 989 In actual fact an array declared without any type but assigned elements of mixed types will be inferred by Swift as being of AnyObject type let mixedArray A String 432 34 989 The use of AnyObject should be used with care since the use of AnyObject masks from Swift the true type of the elements in such an array thereby leaving code prone to potential programmer error It will often be necessary for example to manually cast the elements in an AnyObject array to the correct type before working with them in code Performing the incorrect cast for a specific element in the array will most likely cause the code to compile without error but crash at runtime Consider for the sake of an example the following mixed type array let mixedArray AnyObject 1 2 45 Hello Assume that having initialized the array we now need to iterate through the integer elements in the array and multiply them by 10 The code to achieve this might read as follows for object in mixedArray print object 10 When entered into Xcode however the above code will trigger a syntax error indicating that it is not possible to multiply operands of type AnyObject and Int In order to remove this error it will be necessary to downcast the array element to be of type Int for object in mixedArray print object as Int 10 The above code will compile without error and work as expected until the final String element in the array is reached at which point the code will crash with the following error Could not cast value of type Swift NSContinuousString to NSNumber The code will therefore need to be

    Original URL path: http://www.techotopia.com/index.php/Working_with_Array_and_Dictionary_Collections_in_Swift_2 (2016-02-13)
    Open archived version from archive

  • Understanding Error Handling in Swift 2 - Techotopia
    declared it can be used within a method when throwing errors Throwing an Error A method or function declares that it can throw an error using the throws keyword For example func transferFile throws In the event that the function or method returns a result the throws keyword is placed before the return type as follows func transferFile throws Bool eBookFrenzy com Purchase the full edition of this iOS 9 App Development Essentials book in eBook 12 99 or Print 39 99 format iOS 9 App Development Essentials Print and eBook ePub PDF Kindle edition contains 105 chapters Once a method has been declared as being able to throw errors code can then be added to throw the errors when they are encountered This is achieved using the throw statement in conjunction with the guard statement The following code declares some constants to serve as status values and then implements the guard and throw behavior for the method let connectionOK true let connectionSpeed 30 00 let fileFound false enum FileTransferError ErrorType case NoConnection case LowBandwidth case FileNotFound func fileTransfer throws guard connectionOK else throw FileTransferError NoConnection guard connectionSpeed 30 else throw FileTransferError LowBandwidth guard fileFound else throw FileTransferError FileNotFound Within the body of the method each guard statement checks a condition for a true or false result In the event of a false result the code contained within the else body is executed In the case of a false result the throw statement is used to throw one of the error values contained in the FileTransferError enumeration Calling Throwing Methods and Functions Once a method or function is declared as throwing errors it can no longer be called in the usual manner Calls to such methods must now be prefixed a the try statement as follows try fileTransfer In addition to using the try statement the call must also be made from within a do catch statement to catch and handle any errors that may be thrown Consider for example that the fileTransfer method needs to be called from within a method named sendFile The code within this method might be implemented as follows func sendFile String do try fileTransfer catch FileTransferError NoConnection return No Network Connection catch FileTransferError LowBandwidth return File Tranfer Speed too Low catch FileTransferError FileNotFound return File not Found catch return Unknown error return Successful transfer The method calls the fileTransfer method from within a do catch statement which in turn includes catch conditions for each of the three possible error conditions In each case the method simply returns a string value containing a description of the error In the event that no error was thrown a string value is returned indicating a successful file transfer Note that a fourth catch condition is included with no pattern matching This is a catch all statement that ensures that any errors not matched by the preceeding catch statements are also handled This is required because do catch statements must be exhaustive in other words constructed so as to

    Original URL path: http://www.techotopia.com/index.php/Understanding_Error_Handling_in_Swift_2 (2016-02-13)
    Open archived version from archive

  • Creating an Interactive iOS 9 App - Techotopia
    with the additional functionality we need When we created our new project Xcode anticipated our needs and automatically created a subclass of UIViewController and named it ViewController In so doing Xcode also created a source code file named ViewController swift Selecting the ViewController swift file in the Xcode project navigator panel will display the contents of the file in the editing pane import UIKit class ViewController UIViewController override func viewDidLoad super viewDidLoad Do any additional setup after loading the view typically from a nib override func didReceiveMemoryWarning super didReceiveMemoryWarning Dispose of any resources that can be recreated As we can see from the above code a new class called ViewController has been created that is a subclass of the UIViewController class belonging to the UIKit framework The next step is to extend the subclass to include the two outlets and our action method This could be achieved by manually declaring the outlets and actions within the ViewController swift file A much easier approach is to use the Xcode Assistant Editor to do this for us With the Main storyboard file selected display the Assistant Editor by selecting the View Assistant Editor Show Assistant Editor menu option Alternatively it may also be displayed by selecting the center button the one containing an image of interlocking circles of the row of Editor toolbar buttons in the top right hand corner of the main Xcode window as illustrated in the following figure Figure 16 6 In the event that multiple Assistant Editor panels are required additional tiles may be added using the View Assistant Editor Add Assistant Editor menu option By default the editor panel will appear to the right of the main editing panel in the Xcode window For example in Figure 16 7 the panel to the immediate right of the Interface Builder panel is the Assistant Editor Figure 16 7 By default the Assistant Editor will be in Automatic mode whereby it automatically attempts to display the correct source file based on the currently selected item in Interface Builder If the correct file is not displayed use the toolbar along the top of the editor panel to select the correct file The small instance of the Assistant Editor icon in this toolbar can be used to switch to Manual mode allowing the file to be selected from a pull right menu containing all the source files in the project eBookFrenzy com Purchase the full edition of this iOS 9 App Development Essentials book in eBook 12 99 or Print 39 99 format iOS 9 App Development Essentials Print and eBook ePub PDF Kindle edition contains 105 chapters Make sure that the ViewController swift file is displayed in the Assistant Editor and establish an outlet for the Text Field object by Ctrl clicking on the Text Field object in the view and dragging the resulting line to the area immediately beneath the class declaration line in the Assistant Editor panel as illustrated in Figure 16 8 Figure 16 8 Upon releasing

    Original URL path: http://www.techotopia.com/index.php/Creating_an_Interactive_iOS_9_App (2016-02-13)
    Open archived version from archive



  •