Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare an extension for the String type.
Swift
extension String [1] { func greet() { print("Hello, \(self)!") } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses or brackets instead of curly braces for the extension body.
✗ Incorrect
In Swift, extensions are declared using the 'extension' keyword followed by the type name and then a pair of curly braces '{ }' to contain the new methods or properties.
2fill in blank
mediumComplete the code to add a computed property 'isLong' to String that returns true if the string length is greater than 10.
Swift
extension String {
var isLong: Bool [1] {
return self.count > 10
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'set' instead of 'get' for a read-only computed property.
Adding parentheses after 'get'.
✗ Incorrect
Computed properties in Swift use 'get' to define the getter block without parentheses.
3fill in blank
hardFix the error in the extension by completing the method signature correctly.
Swift
extension Int {
func squared() -> Int [1] {
return self * self
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses or brackets instead of curly braces after the method signature.
✗ Incorrect
Function bodies in Swift are enclosed in curly braces '{ }'. The method signature must be followed by '{' to start the body.
4fill in blank
hardFill both blanks to add a mutating method 'increment' to Int that increases its value by 1.
Swift
extension Int {
mutating func increment() [1] [2] self += 1
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting curly braces or using '-> Void' incorrectly.
Using 'in' which is for closures, not method bodies.
✗ Incorrect
Mutating methods in Swift structs must have their body enclosed in curly braces '{' and '}'. The '-> Void' is optional and 'in' is used in closures, not here.
5fill in blank
hardFill all three blanks to add a static method 'description' to Double that returns a string describing the type.
Swift
extension Double {
static func description() [1] String [2] {
return "Double type"
[3] Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting the return arrow '->'.
Misplacing or missing curly braces.
Using 'in' which is for closures.
✗ Incorrect
Function return types are indicated with '->'. The method body starts with '{' and ends with '}'. 'in' is not used here.