Search Your Question

Showing posts with label Surebot Technology. Show all posts
Showing posts with label Surebot Technology. Show all posts

Write a program to distinguish lowercase and uppercase character from String in swift

Ans : 

Method 1 : 

let string = "iOSiQA is Very Helpful WebSite to Prepare for iOS Interview."
var output = ""

for chr in string {
    var str = String(chr)
    if str.lowercaseString != str {
        output += str


Method 2 : 

let testString = "iOSiQA is Very Helpful WebSite to Prepare for iOS Interview."
let lowerCase = NSCharacterSet.lowercaseLetterCharacterSet()
let upperCase = NSCharacterSet.uppercaseLetterCharacterSet()

for currentCharacter in testString.utf16 {
  if lowerCase.characterIsMember(currentCharacter) {
    println("Character code \(currentCharacter) is lowercase.")
  } else if upperCase.characterIsMember(currentCharacter) {
    println("Character code \(currentCharacter) is UPPERCASE.")
  } else {
    println("Character code \(currentCharacter) is neither upper- nor lowercase.")


Method 3 : 

let testString = "Åke röstet un café in Владивосток!"
let lowerCase = CharacterSet.lowercaseLetters
let upperCase = CharacterSet.uppercaseLetters

for currentCharacter in testString.unicodeScalars {
    if lowerCase.contains(currentCharacter) {
        print("Character code \(currentCharacter) is lowercase.")
    } else if upperCase.contains(currentCharacter) {
        print("Character code \(currentCharacter) is UPPERCASE.")
    } else {
        print("Character code \(currentCharacter) is neither upper- nor lowercase.")

Method 4 :   to identify character is uppercase or lowercase

extension Character {

        func isUpperCase() -> Bool {
            return CharacterSet.uppercaseLetters.contains(self.unicodeScalars.first!)

        func isLowerCase() -> Bool {
            return CharacterSet.lowercaseLetters.contains(self.unicodeScalars.first!)


Write a program to reverse string in swift

Ans : 

Using Self made function : 

func reverse(_ s: String) -> String {
       var str = ""
       //.String is just like array of characters

       for character in s.characters {
            str = "\(character)" + str
            print ( str)
   return str

print (reverse("!pleH"))

Using Swift Direct method : 

Swift 4.0

let str = "abc"




Optional, Optional Binding, Unwrapping and Optional Chaining

Ans : 

Optional : Optional is swift's powerful feature which come to solve problem of  non-existing value. It is just a type . There are two types as Int (which must has a value) and Int?(which may contain a Int value or may have nil value). It is declared as T? i.e Int?, String?

Forced Unwrapping : Exclamation mark ( ! ) is used to unwrap value.
i.e let optionalInt : Int? = 5
let intVal : Int = 2
optionalInt! + intVal

So we hvae forecfully unwrap optionaInt. That means we tell compiler that optionalInt has a value and extract and use it.

But this is not good practise. If sometimes optionaInt has not value and we try to unwrap, then app will be crashed. A good practise is to check with nil before unwrapping or use optional binding. It checks it has value or not and if and only if it has value extract it and use it.

Optional Binding : You use optional binding to check if the optional contains a value or not. If it does contain a value, unwrap it and put it into a temporary constant or variable.

Example :

var stockCode:String? = findStockCode("Facebook")

let text = "Stock Code - "

if let tempStockCode = stockCode {

    let message = text + tempStockCode


The “if let” (or “if var”) are the two keywords of optional binding. In plain English, the code says “If stockCode contains a value, unwrap it, set its value to tempStockCode and execute the conditional block. Otherwise, just skip it the block”. As the tempStockCode is a new constant, you no longer need to use the ! suffix to access its value.

Implicitly Unwrapped Optional : When we are very very sure about it has value after first time it is set, then we need not unwrap every time. So for this type of scenario, we have to use it with ! mark in their type.

// forced unwrapping
let optionalInt: Int? = 123
let forcedInt: Int = optionalInt!

// implicitly unwrapped optional
let assumedInt: Int! = 123
let implicitInt: Int = assumedInt

It may has nil value.

Optional Chaining :

The feature allows us to chain multiple optionals together with the “?.” operator.

if let sharePrice = findStockCode("Apple")?.price {

    let totalCost = sharePrice * 100



FindstockCode method returns optional value. We can access multiple optional together using Optional chaining feature.

What is delegate?

Ans : Delegate is means of communication between objects of iOS Applications. Delegate allows one object to send message to another object when an event occurs.

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@”title” message:@”message” delegate:self cancelButtonTitle:@”Ok” otherButtonTitle:nil];

Here delegate is self. So now self is responsible for handling  all event fired by this instance of UIAlertView class.

Which button of UIAlertView is clicked, for that, event is clickedButtonAtIndex is called in or by Self or currentViewController.

Create PreDefined delegate :

  1. There are two ViewController NameVC and SurNameVC.
  2.  In NameVC, there are 2 textfield named as Name and FullName and 1 button as Submit.
  3. If I write in name and click on submit, it went to SurNameVC to take Surname parameter.
  4. On SurNameVC, after write Surname, on clicking of Submit, It call delegate method and went back to NameVC and Print Full Name in FullName textfield.

Implement above delegate and protocol in Objective-C : 

I have made protocol on SurNameVC like
    @protocol SurNameVCDelegate
      -(void)setSurName:(NSString *) strSurName;
    @property (nonatomic, retain) id delegate;

Now on NameVC submit button click, choose delegate of  SurNameVC object as self.

   objSurNameVC.delegate = self

and create method -(void)setSurName:(NSString *) strSurName;

on NameVC and it is called from surNameVC submit button. So setSurName is delegate method. We can print fullname by concatenating Name and Surname in FullName textfield.

So we delegate just pass message from one view controller to another view controller by delegate method.

Implement delegate and protocol in Swift

I have made custom UISlider. I want to send some value from custom UISlider value changed to view controller in which it is used. So for that, I have used delegate - protocol method.

customSlider.swift  Custom Slider file

import UIKit
protocol SliderDelegate: class {
    func sliderValueChanged(_ sender : UISlider)

class mpgpsSlider: UIView {
      weak var delegateSliderDelegate?

      required init?(coder aDecoder: NSCoder) {

        super.init(coder: aDecoder)
        let bundle = Bundle.init(for: type(of: self))
        let nib = UINib(nibName: "Slider", bundle: bundle)
        let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
        view.frame = bounds
        view.autoresizingMask = [.flexibleWidth,.flexibleHeight]
        slider.addTarget(self, action: #selector(sliderValueChanged(_:)), for:                  .valueChanged)

     @objc func sliderValueChanged(_ sender : UISlider)  {


ViewController.swift ViewController in which custom slider is used.

import UIKit

class VehicleProfileVC: BaseViewController,SliderDelegate{
    override func viewDidLoad() {
        slider.delegate = self
    func sliderValueChanged(_ sender: UISlider) {
        label.text = String(sender.value)

UITableview and UICollectionview

Similarity :
The way to setup both with cell registration, dequeing cells, specifying size and heights are pretty much the same.

Diffrence :
1. The collection view is much more robust in terms of layout features and other things like animations.
Tableiw is a simple list, which displays single-dimensional rows of data. It’s smooth because of cell reuse and other magic.

2. UICollectionView is the model for displaying multidimensional data . 
UITableViewhas a couple of styles of cells stacked one over the other. You should not try to bend it to do any other kind of things too much complex than that kind of layout.

3. UICollectionView is a much more powerful set of classes that allow modifying almost every aspect of how your data will appear on the screen, especially its layout but also other things.

Advantage of Collectionview :
The biggest advantage of using collection view is the ability to scroll horizontally.
 If you want multiple columns in your apps then UICollectionView is the best way to do it. 

It is possible to have multiple columns in table view as well but it gets really messy since you are dealing with and array to display data in a table view.

UICollectionView Supports complex layouts. Apple provides you with something called UICollectionViewDelegateFlowLayout which provides you the flow of left and right as well as up and down.

UICollectionView supports custom animations based on different layouts which again cannot be done in UITableView.

Disadvantage of Collectionview (Advantage of Tablvieview over) :

Major disadvantages of using UICollectionView is auto sizing of your cells. It takes a lot of trial and error to get auto sizing to work correctly. UITableView wins here as all you have to do is return UITableView automatic dimensions for the height of your row in each one of your cells.

Summary :
If you need more control over your layout, go with UICollectionView, If you need simple list go with UITableview.