Quantcast
Channel: 懒得折腾
Viewing all articles
Browse latest Browse all 764

Swift Interview Questions and Answers

$
0
0

Even though Swift is only a year old, it’s already one of the most popular languages. Its syntax looks very easy — so easy that when it was announced JavaScript developers felt like the image to the right.

In reality, Swift, is a complex language. It embraces both object oriented and functional approaches, and it’s still evolving with each new release.

There’s a lot to Swift – but how can you test how much you’ve learned? In this article, the raywenderlich.com Tutorial Team and I have put together a list of sample Swift interview questions.

You can use these questions to interview candidates to test their Swift knowledge, or test your own! And if you don’t know the answer, don’t worry: each question has a solution so you can learn.

The questions are split into two sections:

  • Written questions: Good to include in a take-by-email programming test, since it sometimes involves writing a bit of code.
  • Verbal questions: Good to ask over the phone or in a face-to-face interview, as they can be answered more easily verbally.

Also, each section is split into three levels:

  • Beginner: Suitable for a beginner to Swift, who’s read a book or two on the subject and started working with Swift in their own apps.
  • Intermediate: Suitable for someone who’s got a strong interest in language concepts, who has been reading a lot of blog posts about Swift and experimenting with it further.
  • Advanced: Suitable for the best of the best only – folks who enjoy thoroughly exploring the language, challenging themselves, and using the cutting-edge techniques.

If you want to try answering these questions, I suggest you keep a Playground open to play with the code attached to the question before answering. Answers were tested against Xcode 7.0 beta 5.

Ready? Buckle up, it’s time to go!

Note: Special thanks to raywenderlich.com Tutorial Team members Warren Burton, Greg Heo, Mikael Konutgan, Tim Mitra, Luke Parham, Rui Peres, and Ray Wenderlich who helped me come up with some of these questions, and test them for difficulty level.

Written Questions

Beginners

Hello there, padowan. I’ll start you off with the basics.

Question #1 – Swift 1.0 or later
What’s a better way to write this for loop with ranges?

for var i = 0; i < 5; i++ {
  print("Hello!")
}
Solution Inside: Answer Show

Question #2 – Swift 1.0 or later
Consider the following:

struct Tutorial {
  var difficulty: Int = 1
}
 
var tutorial1 = Tutorial()
var tutorial2 = tutorial1
tutorial2.difficulty = 2

What’s the value of tutorial1.difficulty and tutorial2.difficulty? Would this be any different ifTutorial was a class? Why?

Solution Inside: Answer Show

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?
Solution Inside: Answer Show

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
}
Solution Inside: Answer Show

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.

class Address {
  var fullAddress: String
  var city: String
 
  init(fullAddress: String, city: String) {
    self.fullAddress = fullAddress
    self.city = city
  }
}
 
class Person {
  var name: String
  var address: Address
 
  init(name: String, address: Address) {
    self.name = name
    self.address = address
  }
}
 
var headquarters = Address(fullAddress: "123 Tutorial Street", city: "Appletown")
var ray = Person(name: "Ray", address: headquarters)
var brian = Person(name: "Brian", address: headquarters)

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?

I know it

Solution Inside: Answer Show

Intermediate

Now to step up the difficulty and the trickiness. Are you ready?

Question #1 – Swift 2.0 or later
Consider the following:

var optional1: String? = nil
var optional2: String? = .None

What’s the difference between nil and .None? How do the optional1 and optional2 variables differ?

Solution Inside: Answer Show

Question #2 – Swift 1.0 or later
Here’s a model of a thermometer as a class and a struct:

public class ThermometerClass {
  private(set) var temperature: Double = 0.0
  public func registerTemperature(temperature: Double) {
    self.temperature = temperature
  }
}
 
let thermometerClass = ThermometerClass()
thermometerClass.registerTemperature(56.0)
 
public struct ThermometerStruct {
  private(set) var temperature: Double = 0.0
  public mutating func registerTemperature(temperature: Double) {
    self.temperature = temperature
  }
}
 
let thermometerStruct = ThermometerStruct()
thermometerStruct.registerTemperature(56.0)

This code fails to compile. Where? Why?

Tip: Read it carefully and think about it a bit before testing it in a Playground.

Solution Inside: Answer Show

Question #3 – Swift 1.0 or later
What will this code print out and why?

var thing = "cars"
 
let closure = { [thing] in
  print("I love \(thing)")
}
 
thing = "airplanes"
 
closure()
Solution Inside: Answer Show

Question #4 – Swift 2.0 or later
Here’s a global function that counts the number of unique values in an array:

func countUniques<T: Comparable>(array: Array<T>) -> Int {
  let sorted = array.sort(<)
  let initial: (T?, Int) = (.None, 0)
  let reduced = sorted.reduce(initial) { ($1, $0.0 == $1 ? $0.1 : $0.1 + 1) }
  return reduced.1
}

It uses < and == operators, so it restricts T to types that implement, the Comparable protocol.

You call it like this:

countUniques([1, 2, 3, 3]) // result is 3

Rewrite this function as an extension method on Array so that you can write something like this:

[1, 2, 3, 3].countUniques() // should print 3
Solution Inside: Answer Show

Question #5 – Swift 2.0 or later
Here’s a function to calculate divisions given to two (optional) doubles. There are three preconditions to verify before performing the actual division:

  • The dividend must contain a non nil value
  • The divisor must contain a non nil value
  • The divisor must not be zero
func divide(dividend: Double?, by divisor: Double?) -> Double? {
  if dividend == .None {
    return .None
  }
 
  if divisor == .None {
    return .None
  }
 
  if divisor == 0 {
    return .None
  }
 
  return dividend! / divisor!
}

This code works as expected but has two issues:

  • The preconditions could take advantage of the guard statement
  • It uses forced unwrapping

Improve this function using the guard statement and avoid the usage of forced unwrapping.

Solution Inside: Answer Show

Oh, hi there. You’re now at the midpoint and I see you’re going strong. Shall we see how you fare with some advanced questions?

Think you're clever, do you? This is when I step in.

Advanced

Question #1 – Swift 1.0 or later
Consider the following structure that models a thermometer:

public struct Thermometer {
  public var temperature: Double
  public init(temperature: Double) {
    self.temperature = temperature
  }
}

To create an instance, you can obviously use this code:

var t: Thermometer = Thermometer(temperature:56.8)

But it would be nicer to initialize it this way:

var thermometer: Thermometer = 56.8

Can you? How? Hint: it has to do with convertibles, but not convertibles like Camaros and Mustangs :)

Solution Inside: Answer Show

Question #2 – Swift 1.0 or later

Swift has a set of predefined operators that perform different types of operations, such as arithmetic or logic. It also allows creating custom operators, either unary or binary.
Define and implement a custom ^^ power operator with the following specifications:

  • Takes two Ints as parameters
  • Returns the first parameter raised to the power of the second
  • Ignores potential overflow errors
Solution Inside: Answer Show

Question #3 – Swift 1.0 or later
Can you define an enumeration with raw values like this? Why?

enum Edges : (Double, Double) {
  case TopLeft = (0.0, 0.0)
  case TopRight = (1.0, 0.0)
  case BottomLeft = (0.0, 1.0)
  case BottomRight = (1.0, 1.0)
}
Solution Inside: Answer Show

Question #4 – Swift 2.0 or later
Consider the following code that defines Pizza as a struct and Pizzeria as a protocol, with an extension that includes a default implementation for the method makeMargherita():

struct Pizza {
  let ingredients: [String]
}
 
protocol Pizzeria {
  func makePizza(ingredients: [String]) -> Pizza
  func makeMargherita() -> Pizza
}
 
extension Pizzeria {
  func makeMargherita() -> Pizza {
    return makePizza(["tomato", "mozzarella"])
  }
}

You’ll now define the restaurant Lombardi’s as follows:

struct Lombardis: Pizzeria {
  func makePizza(ingredients: [String]) -> Pizza {
    return Pizza(ingredients: ingredients)
  }
  func makeMargherita() -> Pizza {
    return makePizza(["tomato", "basil", "mozzarella"])
  }
}

The following code creates two instances of Lombardi’s. Which of the two will make a margherita with basil?

let lombardis1: Pizzeria = Lombardis()
let lombardis2: Lombardis = Lombardis()
 
lombardis1.makeMargherita()
lombardis2.makeMargherita()
Solution Inside: Answer Show

Question #5 – Swift 2.0 or later
The following code has a compile time error. Can you spot where and why it happens?

struct Kitten {
}
 
func showKitten(kitten: Kitten?) {
  guard let k = kitten else {
    print("There is no kitten")
  }
 
  print(k)
}

Hint: There are three ways to fix it.

Solution Inside: Answer Show

Verbal Questions

Yeah, that's right...I'm a Swift jedi
You’re good, but you can’t claim jedi status yet. Anybody can figure out the code, but how do you do with more open-ended questions of theory and practice?

To answer some of them you still might need to play with the code in a Playground.

Beginners

Question #1 – Swift 1.0 or later
What is an optional and what problem do optionals solve?

Solution Inside: Answer Show

Question #2 – Swift 1.0 or later
When should you use a structure, and when should you use a class?

Solution Inside: Answer Show

Question #3 – Swift 1.0 or later
What are generics and what problem do they solve?

Solution Inside: Answer Show

Question #4 – Swift 1.0 or later
There are a few cases when you can’t avoid using implicitly unwrapped optionals. When? Why?

Solution Inside: Answer Show

Question #5 – Swift 1.0 or later
What are the various ways to unwrap an optional? How do they rate in terms of safety?
Hint: There are six ways.

Solution Inside: Answer Show

cant believe

Intermediate

Time to rachet up the challenge here. Seems you’re doing just fine so far, but let’s see if you make it through these questions.

Question #1 – Swift 1.0 or later
Is Swift an object-oriented language or a functional language?

Solution Inside: Answer Show

Question #2 – Swift 1.0 or later
Which of the following features are included in Swift?

  1. Generic classes
  2. Generic structs
  3. Generic protocols
Solution Inside: Answer Show

Question #3 – Swift 1.0 or later
In Objective-C, a constant can be declared like this:

const int number = 0;

Here is the Swift counterpart:

let number = 0

Is there any difference between them? If yes, can you explain how they differ?

Solution Inside: Answer Show

Question #4 – Swift 1.0 or later
To declare a static property or function you use the static modifier on value types. Here’s an example for a structure:

struct Sun {
  static func illuminate() {}
}

For classes, it’s possible to use either the static or the class modifier. They achieve the same goal, but in reality they’re different. Can you explain how they differ?

Solution Inside: Answer Show

Question #5 – Swift 1.0 or later
Can you add a stored property by using an extension? Explain.

Solution Inside: Answer Show

Advanced

Oh boy, you’re a clever one, aren’t you? It’s time to step it up another notch.

Question #1 – Swift 1.2
In Swift 1.2, can you explain the problem with declaring an enumeration with generic types? Take for example anEither enumeration with two generic types T and V, with T used as the associated value type for a Left case and V for a Right case:

enum Either<T, V> {
  case Left(T)
  case Right(V)
}

Pro tip: Inspect this case in an Xcode project, not in a Playground. Also notice that this question is related to Swift 1.2 so you’ll need Xcode 6.4.

Solution Inside: Answer Show

Question #2 – Swift 1.0 or later
Are closures value or reference types?

Solution Inside: Answer Show

Question #3 – Swift 1.0 or later
The UInt type is used to store unsigned integers. It implements the following initializer for converting from a signed integer:

init(_ value: Int)

However, the following code generates a compile time error exception if you provide a negative value:

let myNegative = UInt(-1)

Knowing that a negative number is internally represented, using two’s complement as a positive number, how can you convert an Int negative number into an UInt while keeping its memory representation?

Solution Inside: Answer Show

Question #4 – Swift 1.0 or later
Can you describe a situation where you might get a circular reference in Swift, and how you’d solve it?

Solution Inside: Answer Show

Question #5 – Swift 2.0 or later
Swift 2.0 features a new keyword to make recursive enumerations. Here is an example of such an enumeration with a Node case that takes two associated value types, T and List:

enum List<T> {
    case Node(T, List<T>)
}

What’s that keyword?

Solution Inside: Answer Show

Where To Go From Here?

Congrats on making it to the end, and don’t feel bad if you didn’t actually know all the answers!

Some of these questions are pretty complicated and Swift is a rich, expressive language. There’s a lot to learn. Moreover, Apple keeps improving it with new features, so even the best of us may not know it all.

To get to know Swift or build upon what you already know, be sure to check out our in-depth, tutorial-rich book,Swift by Tutorials, or sign up for our hands-on tutorial conference RWDevCon!

Of course, the ultimate resource for all aspects of Swift is the official The Swift Programming Language by Apple.

At the end of the day, using a language is the best way to learn it. Just play with it in a Playground or adopt it in a real project. Swift works (almost) seamlessly with Objective-C, so building on an existing project you already know is an excellent way to learn the ins and outs.

Thanks for visiting and working through these questions! Feel free to chime in below with your questions, problems and discoveries. I wouldn’t mind if you wanted to pose some of your own challenges too. We can all learn from each other. See you in the forums!



Viewing all articles
Browse latest Browse all 764

Trending Articles