Complete the code to add a method that returns the square of an Int.
extension Int {
func squared() -> Int {
return self [1] self
}
}The * operator multiplies the integer by itself to get the square.
Complete the code to add a computed property that returns the number of characters in a String.
extension String {
var length: Int {
return [1]
}
}count without self causes an error.length is not a valid property in Swift strings.self.count returns the number of characters in the string instance.
Fix the error in the extension that adds a method to check if an Int is even.
extension Int {
func isEven() -> Bool {
return self [1] 2 == 0
}
}/ instead of modulo causes a type mismatch.The modulo operator % returns the remainder. If remainder is 0 when divided by 2, the number is even.
Fill both blanks to create an extension that returns a new String with the first letter capitalized and the rest lowercase.
extension String {
func capitalizedFirst() -> String {
return self.prefix(1).[1]() + self.dropFirst().[2]()
}
}capitalized() on the first letter only does not work.trimmingCharacters() is unrelated to case changes.uppercased() makes the first letter uppercase, and lowercased() makes the rest lowercase.
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.
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] }
}
}Initialize counts with 0, then filter characters with count greater than 1.