Swift interview questions

Swift quiz questions

  • 1.

    What output will be produced by the code below?

    let i = 101
    
    if case 100...101 = i {
        print("Hello, world!")
    } else {
        print("Goodbye, world!")
    }

     

    Correct answer: "Hello, world!".

    Explanation: Using if case with a range like 100...101 allows us to check whether an integer is inside that range. In this case, it checks whether the value of i (101) is inside the range of numbers 100 and 101 (inclusive), which it is, so "Hello, world!" is printed.

    View
  • 2.

    What output will be produced by the code below?

    func greet(var name: String) {
        name = name.uppercased()
        print("Greetings, \(name)!")
    }
    
    greet("River")

    Correct answer: This code will not compile.

    Explanation: The greet() method declares its name parameter using the var keyword, which was allowed only in old versions of Swift. From Swift 3.0 onwards this construction is no longer valid, so the compiler will refuse to build this code.

     

    View
  • 3.

    What output will be produced by the code below?

    let names: [String?] = ["Barbara", nil, "Janet", nil, "Peter", nil, "George"]
    
    if let firstName = names.first {
        print(firstName)
    }

    Correct answer: Optional("Barbara").

    Explanation: The names array contains values of type String?, but names.first adds an extra level of optionality because it will return nil if there are no items in the array. So, in this code names.first will return String?? (an optional optional String), of which one layer is unwrapped using the if let.

     

    View
  • 4.

    Once this code is executed, how many items will be in the result array?

    let names: [String?] = ["Barbara", nil, "Janet", nil, "Peter", nil, "George"]
    let result = names.flatMap { $0 }

    Correct answer: 4.

    Explanation: Swift's flatMap will automatically strip nil values from an array, meaning that result will contain the names Barbara, Janet, Peter, and George.

     

    View
  • 5.

    Which loop prints the most lines?

    import Foundation
    let data: [Any?] = ["Bill", nil, 69, "Ted"]
    
    for datum in data where datum is String? {
        print(datum)
    }
    
    for case let .some(datum) in data where datum is String {
        print(datum)
    }

    Correct answer: The first loop prints more lines than the second.

    Explanation: There is a very subtle difference between the two loops, and it's triggered by the data type of the array: this is an array of Any? not an array of strings. The first loop will attempt to typecast its items as String?, which means the loop element must either be a string or nil – that's true of three items. The second loop, however, begins by unwrapping the optional, so it will either be Any or String, at which point our where clause will work. So, the second loop prints two lines.

    View
  • 6.

    What output will be produced by the code below?

    let names = ["Pilot": "Wash", "Doctor": "Simon"]
    let doctor = names["doctor"] ?? "Bones"
    print(doctor)

    Correct answer: "Bones".

    Explanation: The code accesses the "doctor" element in the names dictionary, which is not set: dictionaries are case-sensitive. This will cause nil to be returned, which then triggers the nil coalescing operator to set doctor to be "Bones".

    View
  • 7.

    What output will be produced by the code below?

    var i = 1
    
    mainLoop: repeat {
        i += 2
    
        switch i % 2 {
        case 0:
            break mainLoop
        default:
            break
        }
    } while true
    
    print("Complete!")

    Correct answer: This code will compile but crash.

    Explanation: The main repeat loop is set to loop forever, or at least until someone calls break on it. In the code, this happens only when i % 2 is 0, i.e. when it's an even number, which can never happen because we start with 1 and also add 2. So, even though it will take a long time, the i variable will eventually overflow and trigger a crash.

    View
  • 8.

    When this code is executed, how many items will the names array contain?

    var names = [String]()
    names.reserveCapacity(2)
    names.append("Amy")
    names.append("Rory")
    names.append("Clara")

    Correct answer: 3.

    Explanation: The reserveCapacity() method is there to let you give an indication of how many elements you intend to store in an array, but it does not place any sort of limit.

    View
  • 9.

    What output will be produced by the code below?

    import Foundation
    let rounded: Int = round(10.5)
    print("Rounding 10.5 makes \(rounded)")

    Correct answer: This code will not compile.

    Explanation: The round() method accepts a Double and returns a Double, or accepts a Float and returns a Float. This code creates rounded as an integer then tries to force the result of round() into it, which is not allowed without a typecast.

    View
  • 10.

    What output will be produced by the code below?

    import Foundation
    let crew = NSMutableDictionary()
    crew.setValue("Kryten", forKey: "Mechanoid")
    print(crew.count)

    Correct answer: 1.

    Explanation: Although we've declared the NSMutableDictionary to be constant, it's a reference type and so will happily mutate itself regardless of its supposed "constant" status. So, this code will output 1 because the value was added successfully.

    View
  • 11.

    What output will be produced by the code below?

    let numbers = [1, 3, 5, 7, 9]
    let result = numbers.map { $0 * 10 }
    print(numbers)

    Correct answer: 1, 3, 5, 7, 9.

    Explanation: The call to map will multiply each integer in the numbers array by 10, and assign the result to the result constant. However, the value that is printed is numbers, not result, so the original integers will be printed.

    View
  • 12.

    What output will be produced by the code below?

    let foo = 0x10
    print(foo)

    Correct answer: 16.

    Explanation: Swift lets you declare numbers using 0x as a hexadecimal prefix. 0x10 is 16 in hexadecimal.

    View
  • 13.

    What output will be produced by the code below?

    var spaceships = Set<String>()
    spaceships.insert("Serenity")
    spaceships.insert("Enterprise")
    spaceships.insert("TARDIS")
    spaceships.insert("Serenity")
    print(spaceships.count)

    Correct answer: 3.

    Explanation: Sets are similar to arrays, although each item can only appear once. If you add an item more than once, it will be silently ignored.

     

    View
  • 14.

    What output will be produced by the code below?

    let userLoggedIn: Bool? = false
    
    if !userLoggedIn! {
        print("Message one")
    } else {
        print("Message two")
    }

    Correct answer: "Message one".

    Explanation: The (deliberately clumsy) expression !userLoggedIn! means, "force unwrap this boolean, then negate it." The userLoggedIn boolean is set to be false, so it will be true when negated, meaning that "Message one" will be printed.

    View
  • 15.

    What output will be produced by the code below?

    let number = 5
    
    switch number {
    case 0..<5:
        print("First group")
    case 5...10:
        print("Second group")
    case 0...5:
        print("Third group")
    default:
        print("Fourth group")
    }

    Correct answer: "Second group".

    Explanation: Although there are overlapping ranges in this code, Swift will simply find and execute the first one that matches. The first case, 0..<5, will not be matched because it uses the half-open range operator, which excludes the upper bound.

    View
  • 16.

    What output will be produced by the code below?

    let names = ["Simon", "River", "Book"]
    
    names.forEach {
        print($1)
    }

    Correct answer: This code will not compile.

    Explanation: When using forEach you are given each item of an array using the value $0. This code incorrectly tries to use $1, and so will not compile.

    View
  • 17.

    What output will be produced by the code below?

    struct Spaceship {
        var name: String
    
        func setName(_ newName: String) {
            name = newName
        }
    }
    var enterprise = Spaceship(name: "Enterprise")
    enterprise.setName("Enterprise A")
    print(enterprise.name)

    Correct answer: This code will not compile.

    Explanation: The setName() method is attempting to change the name parameter, which is prohibited unless the mutating keyword is used. The correct code should be mutating func setName(_ newName: String).

    View
  • 18.

    What output will be produced by the code below?

    func fizzbuzz(number: Int) -> String {
        switch (number % 3 == 0, number % 5 == 0) {
        case (true, false):
            return "Fizz"
        case (false, true):
            return "Buzz"
        case (true, true):
            return "FizzBuzz"
        default:
            return String(number)
        }
    }
    
    print(fizzbuzz(number: 15))

    Correct answer: "FizzBuzz".

    Explanation: The fizzbuzz() method creates a tuple of two booleans. The first boolean is true if the numberparameter is evenly divisible by 3, and the second is true if it's evenly divisible by 5. The code uses 15, so the tuple will be (true, true), and thus will print FizzBuzz.

     

    View
  • 19.

    What output will be produced by the code below?

    let numbers = Array(1..<10)
    print(numbers.count)

    Correct answer: 9.

    Explanation: This array constructor creates values based on the range from 1 up to (but not including 10). This means it will include the numbers 1, 2, 3, 4, 5, 6, 7, 8, and 9, so the count will be 9.

    View
  • 20.

    When this code is executed, what data type does convertedNumber have?

    let possibleNumber = "1701"
    let convertedNumber = Int(possibleNumber)

    Correct answer: Int?.

    Explanation: Creating an integer from a string will fail if the string does not contain a valid number. So, this constructor returns Int? to give you either a number (on success) or nil (on failure.)

    View

© 2017 QuizBucket.org