0
0
Swiftprogramming~10 mins

Why extensions add capability without modifying in Swift - Test Your Understanding

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

Complete the code to add a method to the String type using an extension.

Swift
extension String {
    func shout() -> String {
        return self.[1]uppercased()
    }
}
Drag options to blanks, or click blank then click option'
A.
B->
C:
D=
Attempts:
3 left
💡 Hint
Common Mistakes
Using '->' or ':' instead of '.' to call a method.
2fill in blank
medium

Complete the code to add a computed property to Int using an extension.

Swift
extension Int {
    var isEven: Bool {
        return self [1] 2 == 0
    }
}
Drag options to blanks, or click blank then click option'
A*
B/
C%
D+
Attempts:
3 left
💡 Hint
Common Mistakes
Using '/' which does division, not remainder.
3fill in blank
hard

Fix the error in the extension that adds a method to Double to square the value.

Swift
extension Double {
    func squared() -> Double {
        return self [1] self
    }
}
Drag options to blanks, or click blank then click option'
A*
B+
C-
D/
Attempts:
3 left
💡 Hint
Common Mistakes
Using '+' or '-' which add or subtract instead of multiply.
4fill in blank
hard

Fill both blanks to create an extension that adds a method to Array of Int to sum only positive numbers.

Swift
extension Array where Element == Int {
    func sumPositive() -> Int {
        return self.filter { $0 [1] 0 }.reduce(0, [2])
    }
}
Drag options to blanks, or click blank then click option'
A>
B+
C-
D*
Attempts:
3 left
💡 Hint
Common Mistakes
Using '-' or '*' in reduce which changes the sum incorrectly.
5fill in blank
hard

Fill all three blanks to create an extension that adds a method to Dictionary to get keys with values above a threshold.

Swift
extension Dictionary where Value: Comparable {
    func keysAbove(_ threshold: Value) -> [Key] {
        return self.filter { $0.value [1] threshold }.map { [2].[3] }
    }
}
Drag options to blanks, or click blank then click option'
A>
B$0
Ckey
Dkeys
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'keys' property which returns all keys, not filtered ones.