Search This Blog

Showing posts with label swift test. Show all posts
Showing posts with label swift test. Show all posts

Sunday, October 8, 2017

Test questions for iOS and Swift. Part 1


Keywords questions


1. Final Keyword

When using with class it means that class cannot be subclassed.
When using with method it mean this method cannot be overridden in subclass.

When try to subclass final class
import UIKit
import Foundation

final class Car {
    
    func drive() {
        print("Let's go!")
    }
}

class MyCar: Car {
    
    override func drive() {
        print("Let's go faster!")
    }
}

let lady = MyCar()
lady.drive()

This code does not compile.



When try to override final method
import UIKit
import Foundation

class Car {
    
    final func drive() {
        print("Let's go!")
    }
}

class MyCar: Car {
    
    override func drive() {
        print("Let's go faster!")
    }
}

let lady = MyCar()
lady.drive()


This code compiles fine.
import UIKit
import Foundation

class Car {
    
    func drive() {
        print("Let's go!")
    }
}

class MyCar: Car {
    
    override func drive() {
        print("Let's go faster!")
    }
}

let lady = MyCar()
lady.drive()
// print("Let's go faster!")

2. Fallthrough Keyword

In swift when using switch operator we don't need provide break in each case statements. So when case value that equal to search value is found then execution of switch if finished. If you need after execution of case statement go to the next case then you should use fallthrough keyword. There is one important thing about fallthrough - it doesn't check condition of next case it just go to the next case body or to default.
let value = 22

switch value {
case 22:
    print("This is 22")
    fallthrough
case 33:
    print("This is 33")
case 7658:
    print("This is 7658")
default:
    print("This is default")
}

// Result of switch:
// This is 22
// This is 33