Search Your Question

String Interpolation in Swift

Ans : 

String interpolation means creating string from mix of constants, variables, literals, expressions.

let length:Float = 3.14
var breadth = 10
var myString = "Area of a rectangle is length*breadth"
print(myString)
myString = "\(myString) i.e. = \(length)*\(breadth)"
print(myString)

Output :

Area of a rectangle is length*breadth
Area of a rectangle is length*breadth i.e. = 3.14*10

Another way of string interpolcation in Swift :

Use the Swift String initializer:
String(format: <#String#>, arguments: <#[CVarArgType]#>)

For example: let stringFromNumber = String(format: "%.2f", number)

Swift 5.0 has super powerful string interpolation : 

1. Normal custom String interpolation

Code for Example :

Using the new string interpolation system in Swift 5.0 we can extend String.StringInterpolation to add our own custom interpolations

extension String.StringInterpolation {
    mutating func appendInterpolation(_ number: Int) {
        let formatter = NumberFormatter()
        formatter.numberStyle = .spellOut

        if let result = formatter.string(from: number as NSNumber) {
            appendLiteral(result)
        }
    }
}

Use : print("My age is \(age).")
Output : My age is twenty nine.
Above custom interpolation tells to convert integer to word.

Amazing....hua.....


We can also write above function as following :

mutating func appendInterpolation(format number: Int) {

So, we can use like : print("Hi, I'm \(format: age)."). So there will be no confusion between default interpolation and custom interpolation.

2. String interpolation with parameters. : 

mutating func appendInterpolation(linkedin: String) {
    appendLiteral("<a href=\"https://linkedin.com/in/\(linkedin)\">@\(linkedin)</a>")}

output :
"You should follow me on linkedin : <a href="https://linkedin.com/in/twostraws">@twostraws</a>.\n"

We can also pass multiple parameters.

3. We can pass auto closure as parameter :


extension String.StringInterpolation {
    mutating func appendInterpolation(_ values: [String], empty defaultValue: String) {
        if values.count == 0 {
            appendLiteral(defaultValue())
        } else {
            appendLiteral(values.joined(separator: ", "))
        }
    }
}

let names  = [String]()

print("Crew: \(names, empty: "None").")



Using @autoclosure means that we can use simple values or call complex functions for the default value. Here defaultValue() function called for set default value.


extension String.StringInterpolation {
    mutating func appendInterpolation(if condition: @autoclosure () -> Bool, _ literal: StringLiteralType) {
        guard condition() else { return }
        appendLiteral(literal)
    }
}

let amIiOSDeveloper = true
print("Swift rocks: \(if: amIiOSDeveloper, "(*)")")
print("Swift rocks \(amIiOSDeveloper ? "(*)" : "")")


Normally we use 2nd print option at above. But due to custom string interpolation, we can directly use 1st print option.


4. String interpolation with custom type (class or struct)

struct Employee {
    var name: String
    var designation: String
}

extension String.StringInterpolation {
    mutating func appendInterpolation(_ emp: Employee) {
        appendLiteral("I am \(amp.name) and my designation is \(amp.designation).")
    }
}

let manan = Employee(name: "Manan", designation: "Senior Software Engineer")
print("\(manan)")

Print("\(manan)") gives output as :

I am Manan and my designation is Senior Software Engineer.

if we use print(manan) then it gives class debug description because here no string interpolation used.

Awesome...
Thanks Swift 5.0...

If you have any comment, question, or recommendation, feel free to post them in the comment section below!  



Difference between Cocoa and Cocoa Touch

And : 

Application Framework For
i) Cocoa is the application framework for Mac OS X.
ii) Cocoa Touch is the application framework for iPhone and iPod Touch.
Frameworks
i) Cocoa: Foundation and AppKit.
ii) Cocoa Touch: Foundation and UIKit
Absence of certain classes
Cocoa has NSHost and Cocoa Touch doesn't
API
i) Cocoa: All the classes used in Cocoa have the NS prefix Ex: NSTextField
ii) Cocoa Touch: classes used in Cocoa have the UI prefix Ex: UITextField
MVC patterns
i) Cocoa: Cocoa has multiple alternative design patterns – in addition to MVC
ii) Cocoa Touch: The iPhone SDK has a reinforced MVC system, which performs better than the default MVC in Cocoa
Other Differences
There Are also Differences In App Lifecycle, Sandboxing ,Memory Footprint

Difference between POP and OOP

Ans : 

POP - Protocol oriented programming
OOP - Object oriented programming

Swift has both power. POP has more advanced features having object oriented feature itself.



Base class of different class or views

Ans :

Base class of

UITableView : UIScrollView : UIView : UIResponder : NSObject
UIButton : UIControl : UIView : UIResponder : NSObject
NSObject : It is top most super class in swift. NSObject class confirm NSObject protocol.

Q : Is it compulsory to mention NSObject in swift inheritance?
A : No. Any class which is not inheriting any other class have NSObject as super class by default.


How to handle error in Swift?

Ans : 

Error Protocol is just a type for representing error values that can be thrown.

Lets declare our custom error enum by confirming Error protocol.

enum UserDetailError: Error {
        case noValidName
        case noValidAge
}

Now we make one function that throw our error type.

func userTest(age: Int, name: String) throws {
    
    guard age > 0 else {
           throw UserDetailError.noValidAge
    }
    
    guard name.count > 0 else {
           throw UserDetailError.noValidName
    }
}

In function signature, throws keyword is used and in function throw keyword is used to throw error.

Now we cal our function userTest that can throw error.

do{
       try userTest(age: -1, name: "")
}
catch UserDetailError.noValidName
{
        print("The name isn't valid")
}
catch UserDetailError.noValidAge
{
         print("The age isn't valid")
}
catch let error {
          print("Unspecified Error: \(error)")
}


Swift try, try? and try! 

  • Swift try is the most basic way of dealing with functions that can throw errors. try is only used within a do-catch block. However, try? and try! can be used without it.
  • try? is used to handle errors by converting the error into an optional value. This way if an error occurs, the function would return a nil and we known Optionals can be nil in Swift. Hence for try? you can get rid of do-catch block. 
  • try! is used to assert that the error won’t occur. Should be only used when you’re absolutely sure that the function won’t throw an error. Like try?, try! works without a do-catch block.

var t1 = try? Student(name: nil)
var t2 = try! Student(name: "Anupam")



Some truths about protocol

Q1 : Can structure confirm protocol?
A1 : Yes

Q2 : Can enumeration confirm protocol?
A2 : Yes

Q3 : Can we declare variable in protocol?
A3 : Yes -> It must be var and it must be read-Only or readAndWrite . Property declaration is like following : 

protocol someprotocol {
     var gettable : Int { get }
      var setAndGettable : Int { get set }

Q4 : Can we add function in the enumeration?
A4 : Yes

Q5 : Can protocol has own init method?
A5 : Yes

Q6 : Can protocol inherit another protocol?
A6 : Yes
protocol someprotocol : anotherprotocol {

}

Q7: Can we make a class-specific protocol?
A7: You can limit protocol adoption to class types (and not structures or enumerations) by adding the AnyObject or class protocol to a protocol’s inheritance list.

protocol someprotocol : AnyObject, Someanotherprotocol {
}

Now someprotocol can only be confirmed by class type. No structure or enum type can confirm this protocol.

Q8. Can we declare an optional protocol method in swift?
A8. Yes. In that protocol name and optional methods should be followed by @objc due to it consider as objective c code.

@objc protocol someprotocol {
        @objc optional func somemethod()
        @objc optional var someName : String { get set }
}

or 

We can make protocol extension and provide default body to protocol method. So any class or struct confirms that protocol doesn't require implementing that method.

Q.9 Can protocol be fileprivate?

A9. Yes. Protocol can be fileprivate, private, public. Private and fileprivate protocol can be confirmed only within current file.

Q.10 Can we define property in extension?
A10. Swift doesn’t support stored properties inside the extension. Computed property is allowed in extension.

Q.11 Can we define property in protocol?
A.11 Property in protocol must have explicit { get } or { get set } specifier. 

protocol VoiceAssistant {
        var s : String // Not allowed
        var name: String {get} // Allowed
        var voice: String {get set} // Allowed

    }

Q.12 Can we declare same name property in protocol and its extension with different datatype?
A.12 Yes. Extension declared property must have valid getter method.

protocol VoiceAssistant {
   
    var name: String {get}
    var voice: String {get set}
}

extension VoiceAssistant {
    var name: Int {get { return 5}}

}

Q.13 Can we define body in method in protocol? How?
A.13 Yes.

protocol VoiceAssistant {
    func makeMessage()
}

extension VoiceAssistant {
    func makeMessage() {
        print("Default make message method")
    }

}


How to save image in NSUserDefault?

Ans : 

NSUserDefault support format NSData for save. So convert image into NSData and then save.

Save image in NSUserDefault :

    let defaults = NSUserDefaults.standardUserDefaults()
   var imgData = UIImageJPEGRepresentation(image, 1)

   defaults.setObject(imgData, forKey: "image")


Get image from NSUserDefault :

    let defaults = NSUserDefaults.standardUserDefaults()
      if let imgData = defaults.objectForKey("image") as? NSData
      {
         if let image = UIImage(data: imgData)
           {
               self.imageView.image = image
           }

      }

What is new in Swift 5?

Ans : 

1. Abi stability : ABI stability means locking down the ABI to the point that future compiler versions can produce binaries conforming to the stable ABI. It enables binary compatibility between applications and libraries compiled with different Swift versions.

2. App thinning(smaller app size)

3. Powerful swift standard library

4. Powerful swift package manager

5. Powerfully swift compiler

Swift 5 is released with xCode 10.2. It is most powerful version till now.

What is singleton class? Pros and Cons.

Ans : The singleton pattern guarantees that only one instance of a class is instantiated. We are aware of following singleton classes,

// Shared URL Session
let sharedURLSession = URLSession.shared

// Default File Manager
let defaultFileManager = FileManager.default

// Standard User Defaults
let standardUserDefaults = UserDefaults.standard

Above classes are instantiate only once, if we try to create another instance, it returns also first instance. So through out application, only one instance is generated for singleton class.

Custom Singleton Class example: 

Different ways : 
1. When we need default configuration  (Using closure) : 

class NetworkManager {

    // MARK: - Properties

    private static var sharedNetworkManager: NetworkManager = {
        let networkManager = NetworkManager(baseURL: API.baseURL)
       // ....
       // Configuration
       // ....         return networkManager
    }()

    let baseURL: URL(string : "https://www.iosiqa.com")

    private init(baseURL: URL) {
        self.baseURL = baseURL
    }

    class func shared() -> NetworkManager {
        return sharedNetworkManager
    }
}

Use  : NetworkManager.shared().baseURL 

2. Using only single statement : 


class mpiosapp {
    
    static var shared = mpiosapp()
    let baseURL: URL(string : "https://www.iosiqa.com")
    private init(){}
    

}

Use : mpiosapp.shared.baseURL

Q : When static variable will be deinitialized?
A : Static variable will be deinit when program or app stops working.

Disadvantage of Singleton :

1. One of the main disadvantages of singletons is that they make unit testing very hard. They introduce global state to the application. The problem is that you cannot completely isolate classes dependent on singletons. When you are trying to test such a class, you inevitably test the Singleton as well. When unit testing, you want the class to be as loosely coupled with other classes as possible and all the dependencies of the class should be ideally provided externally (either by constructor or setters), so they can be easily mocked. Unfortunately, that is not possible with singletons as they introduce tight coupling and the class retrieves the instance on its own. But it gets even worse. The global state of stateful singletons is preserved between test cases.

2. It is static so memory will not be freeze until app will killed. It has it's own creation time and its own lifecycle.

3. Singletons create hidden dependencies. As the Singleton is readily available throughout the code base, it can be overused. Moreover, since its reference is not completely transparent while passing to different methods, it becomes difficult to track. (To solve that we should pass singleton object variable as parameter and this way is called dependency injection).



Write program of fast enumeration in swift

Ans : 


  1. enum Beverage: CaseIterable {
  2. case coffee, tea, juice
  3. }
  4. let numberOfChoices = Beverage.allCases.count
  5. print("\(numberOfChoices) beverages available")

  1. for beverage in Beverage.allCases {
  2. print(beverage)
  3. }