Swift : Programming Language

Skill Test Set 4: Functions

  1. What keyword is used before function name to declare a function in Swift?
    No keyword is used.

  2. a. func printName(name: String!) -> Void{ }
    b. function printName(name: String) { }

    Which one of the above two statements is correct?
    a is incorrect.
    b is incorrect.
    Both a & b are incorrect.
    Both a & b are correct.

  3. a. If no return type is mentioned then function returns special value of Type Void.
    b. Void is an empty tuple means a tuple with zero element.
    Both statements are right.
    Only a is right.
    Only b is right.
    Both are wrong.

  4. A function that has a defined return type must always return a value because :
    the statement where function is called will expect a value to be returned, so in case if value is not returned, it could lead to crash.
    it won't allow control to fall out of the bottom of the function without returning a value, and attempting to do so will result in a compile-time error.
    it's a convention to do so otherwise it's fine.
    it will cause a runtime error.

  5. Swift function can return any number of values
    True, because it can return a tuple.
    False, because even a tuple is a single compound value which could have multiple values inside.

  6. The function parameters are constant by default.

  7. func add(value1: Int, value2: Int) -> Int {
    value1 = value1 + value2
    return value1
    add(10, value2: 20)

    What will the output?
    Compile time error
    Runtime crash

  8. Which one of the below function definitions is wrong considering Swift language?

    func haveChar(#string: String, character: Character) -> (Bool) { }
    func mean(numbers: Double...) -> Double { }
    func minMax(array: [Int]) -> (min: Int, max: Int)? { }
    func minMax(array: [Int]) -> (min: Int?, max: Int?) { }

  9. When declaring a function, what symbol is used to indicate that an internal parameter name should also be used as an external parameter?
     _   [underscore]
    @  [at]  
     :    [colon]
    #   [hash]

  10. Which of following statements about functions is wrong?
    In-out parameters might have a default value
    Function might have multiple return values
    Function might not have return values
    Function names might be the same with another but at least one parameter should be different

Note: Answers are not given intentionally.