Thursday, January 18, 2018

Mention what is the characteristics of Switch in Swift?


  • It supports any kind of data, and not only synchronize but also checks for equality
  • When a case is matched in switch, the program exists from the switch case and does not continue checking next cases. So you don’t need to explicitly break out the switch at the end of case
  • Switch statement must be exhaustive, which means that you have to cover all possible values for your variable
  • There is no fallthrough in switch statements and therefore break is not required

switch age {
         case 0...2:
            return "Baby"
         case 2...12:
            return "Child"
         case 13...19:
            return "Teenager"
         case let x where x > 65:
            return "Elderly"
         default:
            return "Normal"
      }
protocol daysofaweek {
   mutating func print()
}

enum days: daysofaweek {
   case sun, mon, tue, wed, thurs, fri, sat 
   mutating func print() {
      switch self {
         case sun:
            self = sun
            print("Sunday")
         case mon:
            self = mon
            print("Monday")
         case tue:
            self = tue
            print("Tuesday")
         case wed:
            self = wed
            print("Wednesday")
         case mon:
            self = thurs
            print("Thursday")
         case tue:
            self = fri
            print("Friday")
         case sat:
            self = sat
            print("Saturday")
         default:
            print("NO Such Day")
      }
   }
}

var res = days.wed
res.print()

Explain what Lazy stored properties is and when it is useful?

A lazy stored property is a property whose initial value is not calculated until the first time it is used. You indicate a lazy stored property by writing the lazy modifier before its declaration.

NOTE
You must always declare a lazy property as a variable (with the var keyword), because its initial value might not be retrieved until after instance initialization completes. Constant properties must always have a value before initialization completes, and therefore cannot be declared as lazy.

Lazy properties are useful when the initial value for a property is dependent on outside factors whose values are not known until after an instance’s initialization is complete. Lazy properties are also useful when the initial value for a property requires complex or computationally expensive setup that should not be performed unless or until it is needed.

The example below uses a lazy stored property to avoid unnecessary initialization of a complex class. This example defines two classes called DataImporter and DataManager, neither of which is shown in full:

  1. class DataImporter {
  2. /*
  3. DataImporter is a class to import data from an external file.
  4. The class is assumed to take a nontrivial amount of time to initialize.
  5. */
  6. var filename = "data.txt"
  7. // the DataImporter class would provide data importing functionality here
  8. }
  9. class DataManager {
  10. lazy var importer = DataImporter()
  11. var data = [String]()
  12. // the DataManager class would provide data management functionality here
  13. }
  14. let manager = DataManager()
  15. manager.data.append("Some data")
  16. manager.data.append("Some more data")
  17. // the DataImporter instance for the importer property has not yet been created

The DataManager class has a stored property called data, which is initialized with a new, empty array of String values. Although the rest of its functionality is not shown, the purpose of this DataManager class is to manage and provide access to this array of String data.

Part of the functionality of the DataManager class is the ability to import data from a file. This functionality is provided by the DataImporter class, which is assumed to take a nontrivial amount of time to initialize. This might be because a DataImporter instance needs to open a file and read its contents into memory when the DataImporter instance is initialized.

It is possible for a DataManager instance to manage its data without ever importing data from a file, so there is no need to create a new DataImporter instance when the DataManager itself is created. Instead, it makes more sense to create the DataImporter instance if and when it is first used.

Because it is marked with the lazy modifier, the DataImporter instance for the importer property is only created when the importer property is first accessed, such as when its filename property is queried:

  1. print(manager.importer.filename)
  2. // the DataImporter instance for the importer property has now been created
  3. // Prints "data.txt"


NOTE
If a property marked with the lazy modifier is accessed by multiple threads simultaneously and the property has not yet been initialized, there is no guarantee that the property will be initialized only once.




List out what are the control transfer statements used in Swift?

Control transfer statements used in Swift includes
  • Continue
  • Break
  • Fallthrough
  • Return

Mention what are the collection types available in Swift?

In Swift, collection types come in two varieties Array and Dictionary

Array: You can create an Array of a single type or an array with multiple types. Swift usually prefers the former one
Example for single type array is,

Var cardName : [String] = [ “Robert” , “Lisa” , “Kevin”]

// Swift can infer [String] so we can also write it as:

Var cardNames = [ “Robert”, “Lisa”, “Kevin”] // inferred as [String]

To add an array you need to use the subscript println(CardNames[0])

Dictionary: It is similar to a Hash table as in other programming language. A dictionary enables you to store key-value pairs and access the value by providing the key

var cards = [ “Robert”: 22, “Lisa” : 24, and “Kevin”: 26]

Mention what is the difference between Swift and ‘Objective-C’ language?

Swift Objective-C
  • In a swift, the variable and constants are declared before their use
  • You have to use “let” keyword for constant and “var” keyword for variable
  • There is no need to end code with semi-colon
  • Concatenating strings is easy in swift and allows to make a new string from a mix of constants,  literals, variables, as well as expressions
  • Swift does not require to create a separate interface like Objective C. You can define classes in a single file (.swift)
  • Swift enables you to define methods in class, structure or enumeration
  • In Swift, you use “ +=” Operator to add an item
  • In objective C, you have to declare variable as NSString and constant as int
  • In objective C, variable is declared as “ and constant as “
  • The code ends with semi-colon
  • In objective C, you have to choose between NSMutableString and NSString for string to be modified.
  • For classes, you create separate interface (.h) and implementation (.m) files for classes
  • Objective does not allow this
  • In C, you use “addObject”: method of NSMutable array to append a new item to an array

Mention what are the features of Swift Programming?


  • It eliminates entire classes of unsafe code
  • Variables are always initialized before use
  • Arrays and integers are checked for overflow
  • Memory is managed automatically
  • Instead of using “if” statement in conditional programming, swift has “switch” function

What is a guard statement in Swift?


  • Guard statements are a nice little control flow statement that can be seen as a great addition if you're into a defensive programming style.
  • Guard basically evaluates a boolean condition and proceeds with program execution if the evaluation is true.
  • A guard statement always has an else clause, and it must exit the code block if it reaches there.


guard let courses = student.courses! else {
    return
}

How should one handle errors in Swift?

The method for handling errors in Swift differ a bit from Objective-C. In Swift, it's possible to declare that a function throws an error. It is, therefore, the caller's responsibility to handle the error or propagate it. This is similar to how Java handles the situation.

You simply declare that a function can throw an error by appending the throws keyword to the function name. Any function that calls such a method must call it from a try block.

func canThrowErrors() throws -> String

//How to call a method that throws an error
try canThrowErrors()

//Or specify it as an optional
let maybe = try? canThrowErrors()

What is a deinitializer in Swift?

If you need to perform additional cleanup of your custom classes, it's possible to define a block called deinit. The syntax is the following:

deinit { //Your statements for cleanup here }

Typically, this type of block is used when you have opened files or external connections and want to close them before your class is deallocated.

What's the syntax for external parameters?

The external parameter precedes the local parameter name.

func yourFunction(externalParameterName localParameterName :Type, ....) { .... }

A concrete example of this would be:

func sendMessage(from name1 :String, to name2 :String) { print("Sending message from \(name1) to \(name2)") }