Complete the code to add a method to the String type using an extension.
extension String {
func shout() -> String {
return self.[1]uppercased()
}
}In Swift, to call a method on self, you use the dot . operator.
Complete the code to add a computed property to Int using an extension.
extension Int {
var isEven: Bool {
return self [1] 2 == 0
}
}The modulo operator % gives the remainder. If remainder is 0 when divided by 2, the number is even.
Fix the error in the extension that adds a method to Double to square the value.
extension Double {
func squared() -> Double {
return self [1] self
}
}To square a number, multiply it by itself using the * operator.
Fill both blanks to create an extension that adds a method to Array of Int to sum only positive numbers.
extension Array where Element == Int {
func sumPositive() -> Int {
return self.filter { $0 [1] 0 }.reduce(0, [2])
}
}Filter selects elements greater than 0, then reduce sums them using '+'.
Fill all three blanks to create an extension that adds a method to Dictionary to get keys with values above a threshold.
extension Dictionary where Value: Comparable {
func keysAbove(_ threshold: Value) -> [Key] {
return self.filter { $0.value [1] threshold }.map { [2].[3] }
}
}Filter keys where value is greater than threshold, then map to get the keys.