Swift: Code Test

  1. What does the following do:

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

    A) Int
    B) Int?
    C) String
    D) Code will compile but crash
    E) Code will not compile
    B) Int?
  2. What does the following code print out(?):

    enum MyError: ErrorType {
    case Broken
    case Busted
    case Nadgered
    }

    func willThrowAnError() {
    throw MyError.Busted
    }

    do {
    try willThrowAnError()
    } catch MyError.Busted {
    print("Code was busted!")
    } catch {
    print("Code just didn't work")
    }

    A. Code was busted.
    B. Code just didn't work.
    C. Won't print anything
    D. This code will not compile.
    E. Will compile but crash.
    D. This code will not compile.

    Explaination: The willThrowAnError() method throws an exception, but it is not marked using the throws keyword. The code should read func willThrowAnError() throws.
  3. What will the following code print out?:
    let names = ["Simon", "River", "Book"]

    names.forEach {
    print($1)
    }





    • D. 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.
  4. What output will be produced by the code below?

    import Foundation

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





    • A. The code does 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.
  5. What output will be produced by the code below?

    let people = [String](count: 2, repeatedValue: "Malkovitch")
    print(people)





    A. ["Malkovitch", "Malkovitch"] (an array).

    Explanation: This array constructor automatically creates as many elements as the count property requests, with each one being set to repeatedValue.
  6. What output will be produced by the code below?
    func greet(inout name: String) {
    name = name.uppercaseString
    print("Greetings, (name)!")
    }

    var name = "Mal"
    greet(name)
    print("Goodbye, (name)!")

    A. "Greetings, Mal!", "Goodbye, MAL!".
    B. "Greetings, MAL!", "Goodbye, MAL!".
    C. "Greetings, MAL!", "Goodbye, Mal!".
    D. This code will not compile.
    E. This code will compile but will crash.
    D. This code will not compile.

    Explanation: The greet() function declares its name parameter to be inout, which means it must be passed in using &. The code should be written greet(&name).
  7. What output will be produced by the code below?

    let point = (556, 0)
    switch point {
    case (let x, 0):
    print("X was (x)")
    case (0, let y):
    print("Y was (y)")
    case let (x, y):
    print("X was (x) and Y was (y)")
    }

    A. "Y was 0"
    B. "X was 556"
    C. "X was 556 and Y was 0"
    D. This code will not compile.
    E. This code will compile but will crash.
    B. "X was 556"


    Explanation: Swift will execute the first case block that matches its switch value. In this case, point is a tuple with the value (556, 0), so the (let x, 0) case will be matched and its message printed.
  8. What output will be produced by the code below?

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





    E. 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.
  9. What output will be produced by the code below?
    let name = "Simon"

    switch name {
    case "Simon":
    fallthrough

    case "Malcom", "Zoe", "Kaylee":
    print("Crew")

    default:
    print("Not crew")
    }




    D. This code does not compile.
    E. This code will compile but will crash.
    A. "Crew"

    Explanation: Swift will correctly match the first case again "Simon", then the fallthrough keyword will cause control to fall into the next case block and print "Crew".
  10. What output will be produced by the code below?

    for i in 1.stride(to: 17, by: 4) {
        print(i)
    }





    C. 1, 5, 9, 13

    • Explanation: stride() is useful to move
    • through a range of numbers. In this instance, it will count from 1 up to
    • (but not including) 17, incrementing by four each time.
  11. What output will be produced by the code below?

    class Starship {
    var name: String

    override init(initialName: String) {
        name = initialName
    }
    }

    let serenity = Starship(initialName: "Serenity")

    print(serenity.name)




    C. This code will not compile.


    Explanation: The init() method is declared using override, but this class does not inherit from anything so the keyword must not be used.
  12. When this code is executed, what will the numbers constant contain?

    let numbers = [1, 2, 3].map { [$0, $0] }





    A. [[1, 1], [2, 2], [3, 3]]

    Explanation: The code loops over every number in the numbers array, and creates a new array for each number that contains that number twice. So, 1 will be converted to [1, 1] and so on.
  13. What output will be produced by the code below?
    let userLoggedIn: Bool? = false

    if !userLoggedIn! {
        print("Message one")

    } else {
        print("Message two")







    }
    • A. "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.
  14. What output will be produced by the code below?

    let i = 3

    switch i {
    case 1:
        print("Number was 1")

    case 2:
        print("Number was 2")

    case 3:
        print("Number was 3")

    }





    B. This code will not compile.

    Explanation: Swift requires all switch statements to be exhaustive. This code will not compile because it does not have a default clause.
  15. (T/F) Swift arrays can be joined together using the + operator, which adds the right-hand array to the end of the left-hand.
    TRUE
  16. What output will be produced by the code below?

    let names = ["Amy", "Rory"]

    for name in names {
    name = name.uppercaseString
    print("HELLO, (name)!")
    }





    E. This code will not compile.

    Explanation: This code will not compile because it modifies name inside the loop. If you want to do this, you must use the var keyword like this: for var name in names.
  17. What output will be produced by the code below?
    class Starship {
    var type: String
    var age: Int
    }

    let serenity = Starship(type: "Firefly", age: 24)
    print(serenity.type)




    C. This code will not compile.

    Explanation: Structs have memberwise initialization as standard, but this is not available to classes. The code will fail to compile because the Starship class has no initializers.
  18. What output will be produced by the code below?

    let names = ["Amy", "Clara"]

    for i in 0 ... names.length {
      print("Hello, (names[i])!")
    }





    • C. This code will not compile.
    • Explanation: Swift arrays do not have a length property; this code should use count. With that replacement the code will compile, however it will then crash
    • because it uses the closed range operator (...), which will cause an
    • out-of-bounds error when reading into the array.
  19. You are using a method named willThrowAnError(), and it is marked using throws because it will always throw the error "Forbidden". Given this context, what output will be produced by the code below?

    do {
            try willThrowAnError()

    } catch {
    print("The error message was: (error)")

    }





    E. "Forbidden"

    Explanation: When in a catch block with no pattern, Swift automatically matches any error and binds it to a local constant called error.
  20. (T/F)When in a catch block with no pattern, Swift automatically matches any error and binds it to a local constant called error.

    TRUE
  21. 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"




    D. This program will not compile.
    E. This code will compile but will crash.
    C. "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.
  22. What output will be produced by the code below?

    for i in 3...1 {
       print(i)
    }




    E. This code will compile but crash.

    Explanation: This code will be compiled successfully, but crash at runtime: Swift does not allow you to generate ranges where the initial value is greater than the end value.
  23. (T/F) When closed range operator (...), Swift does not allow you to generate ranges where the initial value is greater than the end value.
    TRUE
  24. When this code is executed, what is the value of the swift string?
    import Foundation

    let ns = NSString("Hello")
    let swift = String(ns)




    A. This code will not compile.


    Explanation: While it is possible to typecast an NSString into a String using a constructor, it is not possible the other way around. The code should read let ns = NSString(string: "Hello").
  25. 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))")





    • B. 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  the number to be an Integer, which cannot be used by sqrt() unless you typecast it.
  26. What output will be produced by the code below?

    let names = ["Chris", "Joe", "Doug", "Jordan"]







    if let name = names[1] {
    print("Brought to you by (name)")
    }
    D. This code will not compile.

    Explanation: Subscripting an array of strings will return a String rather than a String?, which means it is a compile error to attempt to unwrap it using if let.
  27. What output will be produced by the code below?

    func foo(function: (Int) -> Int) -> Int {
    return function(function(5))
    }


    func bar<T: IntegerType>(number: T) -> T {
    return number * 3
    }

    print(foo(bar))

    A. Nothing.
    B. 45
    C. 15
    D. This code will not compile.
    E. This code will compile but will crash.
    B. 45


    Explanation: This code combines generics and closures to make something that's easy to read but hard to understand. It passes the bar() function into foo() as its only parameter. That bar() method is then called twice: once with 5 as its parameter, and then again with the result from the first call as its parameter. The first call passes in 5, so bar() returns 5 3, i.e. 15. The second call passes in that 15, so bar() returns 15 3, i.e. 45.
  28. What output will be produced by the code below?
    struct Spaceship {
    private(set) var name = "Serenity"
    }

    var serenity = Spaceship()
    serenity.name = "Jayne's Chariot"
    print(serenity.name)





    E. This code will not compile.

    • Explanation: Creating a property using private(set) means that Swift won't let external code modify that property directly. However, the definition of "external code" is a precise one: Swift
    • playgrounds are compiled into a single file when run, and code that exists in the same file as a private property can access it directly.
  29. What output will be produced by the code below?

    var first = [1, 2, 3]
    var second = ["one", "two", "three"]
    var third = Array(Zip2Sequence(first, second))
    print(third)





    A. [(1, "one"), (2, "two"), (3, "three")]

    Explanation: This code creates a Zip2Sequence struct out of two arrays: one containing 1, 2, 3, and another containing "one", "two", "three". The Zip2Sequence will match each item in the first array with the item at the same index in the second array, giving (1, "one") and so on. This is then converted to an array for easier access.
  30. func fetchCrewMember() -> (job: String, name: String) {
    return ("Public Relations", "Jayne")
    }

    let result = fetchCrewMember().0

    A."Public Relations"
    B. "Jayne"
    C. Nothing.
    D. The code will not compile.
    E. The code will compile, but the code will crash.
    A."Public Relations"

    Explanation: Even though we name the elements in fetchCrewMember()'s tuple return value, those elements are still accessible using their numerical index as used in the code.
  31. When this code finishes executing, how many strings will the names array contain?

    let names = [String]()
    names.append("Amy")
    names.append("Clara")
    names.append("Rory")





    D. This code will not compile.


    Explanation: The names array was declared using let, which makes it a constant. This means it is a compile error to try to use append() to add strings to it.
  32. (T/F)  Structs have memberwise initialization as standard, but this is not available to classes.
    TRUE
  33. What output will be produced by the code below?
    let names = ["Amy", "Rory"]
    for name in names {   
    name = name.uppercaseString    print("HELLO, \(name)!")
    }





    C. This code will not compile.

    Explanation: This code will not compile because it modifies name inside the loop. If you want to do this, you must use the var keyword like this:

    for var name in names.
  34. What output will be produced by the code below?
    var i = 2
    do {   
             print(i)    i *= 2

         } while (i < 128)





    C. This code will not compile.

    Explanation: The do keyword is invalid here; the programmer should use repeat instead.
Author
geschw66
ID
322005
Card Set
Swift: Code Test
Description
Select the best answer. Multiple choice.
Updated