IOS, IOS Questions, Swift

Swift Technical Interview Questions and Answers !

Question #1 – Swift 1.0 or later

What’s a better way to write this for loop with ranges?

Answer:

Question #2 – Swift 1.0 or later

What’s the value of tutorial1.difficulty and tutorial2.difficulty?

Answer:
tutorial1.difficulty is 1, whereas tutorial2.difficulty is 2.

Question #3 – Swift 1.0 or later

view1 is declared with var, and view2 is declared with let. What’s the difference here, and will the last line compile?
import UIKit

var view1 = UIView()
view1.alpha = 0.5

let view2 = UIView()
view2.alpha = 0.5 // Will this line compile?

Answer:
view1 is a variable and can be re-assigned to a new instance of UIView. With let you can assign a value only once, so the following code doesn’t compile:
view2 = view1 // Error: view2 is immutable
However, UIView is a class with reference semantics, so you can mutate the properties of view2 (which means the last line will compile):
let view2 = UIView()
view2.alpha = 0.5 // Yes!

Question #4 – Swift 1.0 or later

This code sorts an array of names alphabetically and looks complicated. Simplify it and the closure as much as you can.
let animals = [“fish”, “cat”, “chicken”, “dog”]
let sortedAnimals = animals.sort { (one: String, two: String) -> Bool in
return one < two
}

Answer:
1- let sortedAnimals = animals.sort { (one, two) -> Bool in return one < two }
2- let sortedAnimals = animals.sort { return $0 < $1 }
3- let sortedAnimals = animals.sort(<)
Question #5 – Swift 1.0 or later

This code creates two classes, Address and Person, and it creates two instances to represent Ray and Brian.

Suppose Brian moves to the new building across the street, so you update his record like this:
brian.address.fullAddress = “148 Tutorial Street”
What’s going on here? What’s wrong with this?

Answer:
Ray also moved to the new building! Address is a class and has reference semantics, so headquarters is the same instance, whether you access it via ray or brian. Changing the address of headquarters will change it for both. Can you imagine what would happen if Brian got Ray’s mail or vice versa? :]
The solution is to create a new Address to assign to Brian, or to declare Address as a struct instead of a class.

Source : Raywenderlich

mycodetips

Passionate about coding and software development holding 10+ Years of experience including 6+ years of experience on Mobile application Development.

More Posts