0
0
Swiftprogramming~10 mins

Initializers and designated init 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 define a designated initializer for the class.

Swift
class Person {
    var name: String
    init([1]: String) {
        self.name = name
    }
}
Drag options to blanks, or click blank then click option'
Ainit
Bself
Cvalue
Dname
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'self' or 'init' as parameter names causes errors.
Using a different parameter name without assigning it properly.
2fill in blank
medium

Complete the code to call the designated initializer from a convenience initializer.

Swift
class Vehicle {
    var wheels: Int
    init(wheels: Int) {
        self.wheels = wheels
    }
    convenience init() {
        self.[1](wheels: 4)
    }
}
Drag options to blanks, or click blank then click option'
Asuper
Bself
Cinit
Dconvenience
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'self' without '.init' causes errors.
Using 'super' in a convenience initializer of the same class.
3fill in blank
hard

Fix the error in the initializer by completing the missing keyword.

Swift
class Animal {
    var species: String
    [1] init(species: String) {
        self.species = species
    }
}
Drag options to blanks, or click blank then click option'
Arequired
Bfinal
Coverride
Dconvenience
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'convenience' instead of 'required' changes initializer type.
Omitting the keyword when subclassing requires it.
4fill in blank
hard

Fill both blanks to create a designated initializer with a default parameter value.

Swift
class Book {
    var title: String
    var pages: Int
    init(title: String, pages: [1] = [2]) {
        self.title = title
        self.pages = pages
    }
}
Drag options to blanks, or click blank then click option'
AInt
B100
CString
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using String type for pages causes type errors.
Omitting the default value or using zero when 100 is expected.
5fill in blank
hard

Fill all three blanks to complete the subclass initializer calling the superclass designated initializer.

Swift
class Employee: Person {
    var id: Int
    init(name: String, id: [1]) {
        self.id = id
        super.[2](name: [3])
    }
}
Drag options to blanks, or click blank then click option'
AString
Binit
Cname
DInt
Attempts:
3 left
💡 Hint
Common Mistakes
Using String type for id causes errors.
Calling 'super' without '.init' is invalid.
Passing wrong argument name to superclass initializer.