0
0
Swiftprogramming~10 mins

Why structs are preferred in Swift - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a struct named Person with a name property.

Swift
struct [1] {
    var name: String
}
Drag options to blanks, or click blank then click option'
APerson
Bclass
Cfunc
Dvar
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'class' instead of the struct name.
Using 'func' or 'var' which are not valid struct names.
2fill in blank
medium

Complete the code to create a new instance of the struct Person.

Swift
let person = [1](name: "Alice")
Drag options to blanks, or click blank then click option'
APerson
BPerson()
Cperson
Dstruct
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Person()' with parentheses inside the code incorrectly.
Using 'struct' keyword instead of the struct name.
3fill in blank
hard

Fix the error in the code to correctly copy a struct instance.

Swift
var person1 = Person(name: "Bob")
var person2 = person1
person2.name = [1]
Drag options to blanks, or click blank then click option'
Aperson2.name
Bperson1.name
C"Alice"
DPerson.name
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning from person1.name which does not change the name.
Using Person.name which is invalid syntax.
4fill in blank
hard

Fill both blanks to create a struct with a method that returns a greeting.

Swift
struct Greeter {
    var name: String
    func [1]() -> String {
        return "Hello, \([2])!"
    }
}
Drag options to blanks, or click blank then click option'
Agreet
Bname
CsayHello
Dself
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'sayHello' as method name but not matching the blank order.
Using 'self' instead of the property name inside the string.
5fill in blank
hard

Fill all three blanks to create a struct with a computed property that returns the full name.

Swift
struct User {
    var firstName: String
    var lastName: String
    var fullName: String {
        return [1] + " " + [2]
    }
    func printName() {
        print([3])
    }
}
Drag options to blanks, or click blank then click option'
AfirstName
BlastName
CfullName
Dname
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'name' which is not defined.
Printing 'firstName' or 'lastName' instead of 'fullName'.