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".
  • An Introduction to Swift Playgrounds - Techotopia
    code that reads as follows println Welcome to Swift All that the code does is make a call to the built in Swift println function which takes as a parameter a string of characters to be displayed on the console Those familiar with other programming languages will note the absence of a semi colon at the end of the line of code In Swift semi colons are optional and generally only used as a separator when multiple statements occupy the same line of code Note that after entering the line of code the results panel to the right of the editing panel is now showing the output from the println call as highlighted in Figure 6 2 Figure 6 2 eBookFrenzy com Purchase the fully updated iOS 9 Swift 2 Xcode 7 edition of this 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 Playground Timelines Playgrounds are particularly useful when working and experimenting with Swift algorithms This can be of particular use when combined with the Playground Timeline Assistant Remaining within the playground editor enter the following lines of code beneath the existing println statement var x 10 for index in 1 20 let y index x This expression repeats a loop 20 times performing an arithmetic expression on each iteration of the loop Once the code has been entered into the editor the playground will execute the loop and display in the results panel the number of times the loop was performed More interesting information however may be obtained by hovering the mouse pointer over the results line so that two additional buttons appear as shown in Figure 6 3 Figure 6 3 The left most of the two buttons is the quick look button which when selected will show a popup panel displaying the results as shown in Figure 6 4 Figure 6 4 The right most button is the value history button which when selected displays the results inline with the code Figure 6 5 The slider along the bottom edge of the playground panel can be moved to view the prevailing results at different points in the value history timeline Sliding it to the left for example will highlight and display the different values in the graph Figure 6 6 Working with UIKit in Playgrounds The playground environment is not restricted to simple Swift code statements Much of the power of the iOS 8 SDK is also available for experimentation within a playground When the playground used in this chapter was created it included a line to import the iOS UIKit Framework The UIKit Framework contains most of the classes necessary to implement user interfaces for iOS applications and is an area which will be covered in significant detail throughout the book An extremely powerful feature of playgrounds is that it is also possible to work with UIKit along with many of the other Frameworks that comprise the iOS

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


  • Swift Data Types, Constants and Variables - Techotopia
    scalar where nn is replaced by two hexadecimal digits representing the Unicode character u nnnn Double byte Unicode scalar where nnnn is replaced by four hexadecimal digits representing the Unicode character U nnnnnnnn Four byte Unicode scalar where nnnnnnnn is replaced by four hexadecimal digits representing the Unicode character Swift Variables Variables are essentially locations in computer memory reserved for storing the data used by an application Each variable is given a name by the programmer and assigned a value The name assigned to the variable may then be used in the Swift code to access the value assigned to that variable This access can involve either reading the value of the variable or changing the value It is of course the ability to change the value of variables which gives them the name variable Swift Constants A constant is similar to a variable in that it provides a named location in memory to store a data value Constants differ in one significant way in that once a value has been assigned to a constant it cannot subsequently be changed Constants are particularly useful if there is a value which is used repeatedly throughout the application code Rather than use the value each time it makes the code easier to read if the value is first assigned to a constant which is then referenced in the code For example it might not be clear to someone reading your Swift code why you used the value 5 in an expression If instead of the value 5 you use a constant named interestRate the purpose of the value becomes much clearer Constants also have the advantage that if the programmer needs to change a widely used value it only needs to be changed once in the constant declaration and not each time it is referenced As with variables constants have a type a name and a value Unlike variables however once a value has been assigned to a constant that value cannot subsequently be changed Declaring Constants and Variables Variables are declared using the var keyword and may be initialized with a value at creation time If the variable is declared without an initial value it must be declared as being optional a topic which will be covered later in this chapter The following for example is a typical variable declaration var userCount 10 Constants are declared using the let keyword let maxUserCount 20 For greater code efficiency and execution performance Apple recommends the use of constants rather than variables whenever possible Type Annotations and Type Inference Swift is categorized as a type safe programming language This essentially means that once the data type of a variable has been identified that variable cannot subsequently be used to store data of any other type without inducing a compilation error This contrasts to loosely typed programming languages where a variable once declared can subsequently be used to store other data types There are two ways in which the type of a constant or variable will be identified One approach is to use a type annotation at the point the variable or constant is declared in the code This is achieved by placing a colon after the constant or variable name followed by the type declaration The following line of code for example declares a variable named userCount as being of type Int var userCount Int 10 In the absence of a type annotation in a declaration the Swift compiler uses a technique referred to as type inference to identify the type of the constant or variable When relying on type inference the compiler looks to see what type of value is being assigned to the constant or variable at the point that it is initialized and uses that as the type Consider for example the following variable and constant declarations var signalStrength 2 231 let companyName My Company During compilation of the above lines of code Swift will infer that the signalStrength variable is of type Double type inference in Swift defaults to Double for all floating point numbers and that the companyName constant is of type String When a constant is declared without a type annotation it must be assigned a value at the point of declaration let bookTitle iOS 8 Development Essentials If a type annotation is used when the constant is declared however the value can be assigned later in the code For example let bookTitle String if iosBookType bookTitle iOS 8 Development Essentials else bookTitle Android Studio Development Essentials It is important to note that a value may only be assigned to a constant once A second attempt to assign a value to a constant will result in a syntax error The Swift Tuple Before proceeding now is a good time to introduce the Swift tuple The tuple is perhaps one of the simplest yet most powerful features of the Swift programming language A tuple is quite simply a way to temporarily group together multiple values into a single entity The items stored in a tuple can be of any type and there are no restrictions requiring that those values all be of the same type A tuple could for example be constructed to contain an Int value a Float value and a String as follows let myTuple 10 432 433 This is a String The elements of a tuple can be accessed using a number of different techniques A specific tuple value can be accessed simply by referencing the index position with the first value being at index position 0 The code below for example extracts the string resource at index position 2 in the tuple and assigns it to a new string variable let myTuple 10 432 433 This is a String var myString myTuple 2 println myString Alternatively all of the values in a tuple may be extracted and assigned to variables or constants in a single statement let myInt myFloat myString myTuple This same technique can be used to extract selected values from a tuple whilst

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

  • Swift Operators and Expressions - Techotopia
    edition contains 105 chapters Boolean Logical Operators Swift also provides a set of so called logical operators designed to return Boolean true or false values These operators both return Boolean results and take Boolean values as operands The key operators are NOT AND OR and XOR The NOT operator simply inverts the current value of a Boolean variable or the result of an expression For example if a variable named flag is currently true prefixing the variable with a character will invert the value to false var flag true variable is true var secondFlag flag secondFlag set to false The OR operator returns true if one of its two operands evaluates to true otherwise it returns false For example the following code evaluates to true because at least one of the expressions either side of the OR operator is true if 10 20 20 10 println Expression is true The AND operator returns true only if both operands evaluate to be true The following example will return false because only one of the two operand expressions evaluates to true if 10 20 20 10 println Expression is true The XOR operator returns true if one and only one of the two operands evaluates to true For example the following code will return true since only one operator evaluates to be true if 10 20 20 10 println Expression is true If both operands evaluated to be true or both were false the expression would return false Range Operators Swift includes two useful operators that allow ranges of values to be declared As will be seen in later chapters these operators are invaluable when working with looping in program logic The syntax for the closed range operator is as follows x y This operator represents the range of numbers starting at x and ending at y where both x and y are included within the range The range operator 5 8 for example specifies the numbers 5 6 7 and 8 The half closed range operator on the other hand uses the following syntax x y In this instance the operator encompasses all the numbers from x up to but not including y A half closed range operator 5 8 therefore specifies the numbers 5 6 and 7 The Ternary Operator Swift supports the ternary operator to provide a shortcut way of making decisions within code The syntax of the ternary operator also known as the conditional operator is as follows condition true expression false expression The way the ternary operator works is that condition is replaced with an expression that will return either true or false If the result is true then the expression that replaces the true expression is evaluated Conversely if the result was false then the false expression is evaluated Let s see this in action var x 10 var y 20 println Largest number is x y x y The above code example will evaluate whether x is greater than y Clearly this will evaluate to

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

  • Swift Flow Control - Techotopia
    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 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 eBookFrenzy com Purchase the fully updated iOS 9 Swift 2 Xcode 7 edition of this 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 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_Flow_Control (2016-02-13)
    Open archived version from archive

  • The Swift Switch Statement - Techotopia
    a value This is the value against which the switch operates For each possible match a case statement is provided followed by a match value Each potential match must be of the same type as the governing expression Following on from the case line are the Swift statements that are to be executed in the event of the value matching the case condition Finally the default section of the construct defines what should happen if none of the case 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 eBookFrenzy com Purchase the fully updated iOS 9 Swift 2 Xcode 7 edition of this 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 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 case 0 49 where temperature 2 0 println Cold and even case 50 79 where temperature 2 0 println Warm and even case 80 110 where temperature 2 0 println Hot and even default println Temperature out of range or odd Fallthrough Those familiar with switch statements in other languages such as C and Objective C will notice that it is no longer necessary to include a break statement after each case declaration Unlike other languages Swift automatically breaks out of

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

  • An Overview of Swift Functions and Closures - Techotopia
    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 fully updated iOS 9 Swift 2 Xcode 7 edition of this 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_Functions_and_Closures (2016-02-13)
    Open archived version from archive

  • The Basics of Object Oriented Programming in Swift - Techotopia
    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 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 eBookFrenzy com Purchase the fully updated iOS 9 Swift 2 Xcode 7 edition of this 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 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

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

  • An Introduction to Swift Inheritance - Techotopia
    class one that duplicates all of the functionality of the BankAccount class together with the new features required by a savings account A more efficient approach however would be to create a new class that is a subclass of the BankAccount class The new class will then inherit all the features of the BankAccount class but can then be extended to add the additional functionality required by a savings account To create a subclass of BankAccount that we will call SavingsAccount we simply declare the new class this time specifying BankAccount as the parent class class SavingsAccount BankAccount Note that although we have yet to add any instance variables or methods the class has actually inherited all the methods and properties of the parent BankAccount class We could therefore create an instance of the SavingsAccount class and set variables and call methods in exactly the same way we did with the BankAccount class in previous examples That said we 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 func calculateInterest Float return interestRate accountBalance eBookFrenzy com Purchase the fully updated iOS 9 Swift 2 Xcode 7 edition of this 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 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 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

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



  •