Swift interview questions

Swift quiz questions

  • 1.

    What output will be produced by the code below?

    var i = 2
    
    do {
        print(i)
        i *= 2
    } while (i < 128)

    Answer:

    Correct answer: This code will not compile.

    Explanation: The do keyword is invalid here; the programmer should use repeat instead.

    View
  • 2.

    Given the code below, what data type does i have?

    let i = 10.2

    Answer:

    Correct answer: Double.

    Explanation: When given a floating-point number, Swift's type inference will use the Double data type.

    View
  • 3.

    What output will be produced by the code below?

    import Foundation
    let number = 16
    print("\(number) squared is \(number * number), and its square root is \(sqrt(number))")

    Answer: This code will not compile.

    Explanation: The sqrt() function can be called using two different types of parameter, neither of which are integers. In this example, Swift's type inference will consider number to be an Integer, which cannot be used by sqrt()unless you typecast it.

    View
  • 4.

    What output will be produced by the code below?

    final class Dog {
        func bark() {
            print("Woof!")
        }
    }
    
    class Corgi : Dog {
        override func bark() {
            print("Yip!")
        }
    }
    
    let muttface = Corgi()
    muttface.bark()

    Answer:

    Correct answer: This code will not compile.

    Explanation: This code attempts to create a new class, Corgi, that inherits from an existing class, Dog. Ordinarily that would be fine, but here the Dog class has been marked as final, which means it cannot be inherited from.

    View
  • 5.

    What output will be produced by the code below?

    struct Spaceship {
        var name: String {
            willSet {
                print("I'm called \(newValue)!")
            }
        }
    }
    
    var serenity = Spaceship(name: "Serenity")
    serenity.name = "TARDIS"

    Answer:

    Correct answer: "I'm called TARDIS!".

    Explanation: The willSet property observer is triggered only when the initial value is changed, and not when the struct is created using memberwise initialization.

    View
  • 6.

    When this code is executed, what will be the value of the j constant?

    let i = "5"
    let j = i + i

    Answer:

    Correct answer: "55" (a string).

    Explanation: When used with strings, the + operator acts to append one string to another. In this case, it merges "5" onto "5" to make "55"

    View

© 2017 QuizBucket.org