0
0
Swiftprogramming~10 mins

Function declaration syntax in Swift - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a function named greet.

Swift
func [1]() {
    print("Hello!")
}
Drag options to blanks, or click blank then click option'
Agreet
BsayHello
Chello
DprintGreeting
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different function name than requested.
Forgetting to write the function name after func.
2fill in blank
medium

Complete the code to declare a function named add that takes two Int parameters.

Swift
func add(_ a: Int, _ b: Int) -> Int {
    return a [1] b
}
Drag options to blanks, or click blank then click option'
A/
B-
C*
D+
Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction or multiplication instead of addition.
Forgetting to return the result.
3fill in blank
hard

Fix the error in the function declaration to correctly return a String.

Swift
func welcomeMessage(name: String) -> [1] {
    return "Welcome, \(name)!"
}
Drag options to blanks, or click blank then click option'
AString
BBool
CInt
DVoid
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong return type like Int or Bool.
Forgetting to specify the return type.
4fill in blank
hard

Fill both blanks to declare a function that takes a Double and returns its square as Double.

Swift
func square(number: [1]) -> [2] {
    return number * number
}
Drag options to blanks, or click blank then click option'
ADouble
BInt
CString
DBool
Attempts:
3 left
💡 Hint
Common Mistakes
Using different types for parameter and return value.
Using Int instead of Double.
5fill in blank
hard

Fill all three blanks to declare a function that returns a dictionary with keys as uppercase strings and values as their lengths for words longer than 3 letters.

Swift
func wordLengths(words: [String]) -> [String: Int] {
    return words.filter { $0.count [3] 3 }.reduce(into: [String: Int]()) { result, word in result[[1]] = [2] }
}
Drag options to blanks, or click blank then click option'
Aword.uppercased()
Bword.count
C>
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using lowercase words as keys.
Using wrong comparison operators.
Mixing up keys and values.