swiftSwift Code Interview

Classic code questions

What is the output of the following?

struct Author {
    var book: String
    var content: String {
        return book
    }
}

var author = Author(book: "AAA")
var authorCopy = author

author.book = "BBB"

print(author.content, authorCopy.content)

Answer

BBB AAA

What is the output?

class R: NSObject {
    let int: Int
    init(_ int: Int) {
        self.int = int
    }
}

func == (l: R, r: R) -> Bool {
    return l.int == r.int
}

let i1: NSObject = R(2)
let i2: NSObject = R(2)
let i3: R = R(3)
let i4: R = R(3)

print((i1 as? R))
print((i2 as? R))
print((i2 as! R))
print((i2 as! R))
print(i1 == i2, i3 == i4, (i1 as? R) == (i2 as? R), (i1 as! R) == (i2 as! R))

Answer

Optional(<__lldb_expr_76.R: 0x600003e4c210>)
Optional(<__lldb_expr_76.R: 0x600003e48380>)
<__lldb_expr_76.R: 0x600003e48380>
<__lldb_expr_76.R: 0x600003e48380>
false true false true

What is the output of the following?

let numbers: [String?] = ["1", "two", nil]

let mapped: [Any] = numbers.compactMap { $0 }
let intArray: [Int?] = numbers.compactMap { Int($0 ?? "0") }

print(mapped.count)
print(intArray.count)

Answer

2
3

compactMap returns an array containing the non-nil results of calling the given transformation with each element of this sequence.

What is the output of the following?

class A {
    var b: B

    init(b: B) {
        self.b = b
    }

    deinit {
        print("A")
    }
}

class B {
    var a: A?

    deinit {
        print("B")
    }
}

var b: B? = B()
var a: A? = A(b: b!)

b?.a = a
a = nil

Answer

A

What will be printed to the console?

func doSomething() {
    defer { print("a") }
    defer { print("b") }
    defer { print("c") }
    print("d")
}

doSomething()

Answer

d
c
b
a

A defer statement is used for executing code just before transferring program control outside of the scope that the defer statement appears in.

This scope is anything beetween { }, functions, do blocks, loops.

Similar to finally in other languages.

What is the output of the following?

class BaseViewController {
    var view = "" {
        didSet {
            print("Base \(view)")
        }
    }
}

class SubViewController: BaseViewController {
    override var view: String {
        didSet {
            print("Sub: \(view)")
        }
    }
}

let viewController = SubViewController()
viewController.view = "a"
viewController.view = "b"

Answer

Base: a
Sub: a
Base: b
Sub: b

What is the output of the following?

var x = 5

func increment() -> Int {
    defer { x += 1 }
    return x
}

x = increment()
let result = increment()

print(x, result, x)

Answer

6 5 6

What is the output of the following?

let x = 15
var result = 0

switch x {
case 1...15:
    result = 1
    fallthrough
case 2:
    result = 102
case 5:
    result = 103
default:
    result = 104
}

print(result)

Answer

102

The fallthrough keyword simply causes code execution to move directly to the statements inside the next case (or default case) block

Swift has five control transfer statements: continue, break, fallthrough, return, throw.

What is the output of the following?

func check(a: () -> ()) {
    func a() {
        print("a")
    }
    a()
}

func addition(y a: () -> ()) {
    func y() {
        print("y")
    }
    y()
}

check {
    print("Check")
}

addition {
    print("Addition")
}

Answer

a
y

With the new redeclaration inside the closure, the functionality is rewritten.

What is the output of the following?

final class JR {
    func show() {
        print("JR")
    }
}

struct Y {
    var ref = JR()

    mutating func change() -> String {
        ref.show()
        return isKnownUniquelyReferenced(&ref) ? "No copy" : "Copy"
    }
}

let x = Y()
var array = [x]

print(array[0].change(), array[0].ref.show())

Answer

JR
JR
Copy ()

isKnownUniquelyReferenced(_:) returns a Boolean value indicating whether the given object is known to have a single strong reference.

What is the output?

let x: String?? = .some(nil)
let outputX = (x ?? "inner") ?? "outer"

let y: String?? = nil
let outputY = (y ?? "inner") ?? "outer"

print("\(x) \(y) \(outputX) \(outputY)")

Answer

Optional(nil) nil outer inner

What is the output?

func doSomething(number: Int) {
    if number % 2 == 0 {
        defer {
            print("A")
        }
        print("B")
    } else {
        print("C")
    }
    print("D")
}

doSomething(number: 4)

Answer

B
A
D