0
0
Swiftprogramming~10 mins

Extending built-in types 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 add a method that returns the square of an Int.

Swift
extension Int {
    func squared() -> Int {
        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 + instead of * will add the number to itself, not square it.
Using - or / will cause incorrect results or errors.
2fill in blank
medium

Complete the code to add a computed property that returns the number of characters in a String.

Swift
extension String {
    var length: Int {
        return [1]
    }
}
Drag options to blanks, or click blank then click option'
Acount
Bself.length
Clength
Dself.count
Attempts:
3 left
💡 Hint
Common Mistakes
Using just count without self causes an error.
Using length is not a valid property in Swift strings.
3fill in blank
hard

Fix the error in the extension that adds a method to check if an Int is even.

Swift
extension Int {
    func 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 division / instead of modulo causes a type mismatch.
Using multiplication or addition operators will not check evenness.
4fill in blank
hard

Fill both blanks to create an extension that returns a new String with the first letter capitalized and the rest lowercase.

Swift
extension String {
    func capitalizedFirst() -> String {
        return self.prefix(1).[1]() + self.dropFirst().[2]()
    }
}
Drag options to blanks, or click blank then click option'
Auppercased
Blowercased
Ccapitalized
DtrimmingCharacters
Attempts:
3 left
💡 Hint
Common Mistakes
Using capitalized() on the first letter only does not work.
Using trimmingCharacters() is unrelated to case changes.
5fill in blank
hard

Fill all three blanks to create an extension that returns a dictionary with characters as keys and their counts as values, filtering only characters that appear more than once.

Swift
extension String {
    func repeatedCharacters() -> [Character: Int] {
        let counts = self.reduce(into: [:]) { counts, char in
            counts[char, default: [1]] += 1
        }
        return counts.filter { $0.value [2] [3] }
    }
}
Drag options to blanks, or click blank then click option'
A0
B>
C1
D==
Attempts:
3 left
💡 Hint
Common Mistakes
Initializing counts with 1 causes incorrect counts.
Using equality instead of greater than filters only characters appearing exactly once.