0
0
Swiftprogramming~10 mins

Operator overloading concept 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 overload the + operator for the Vector struct.

Swift
struct Vector {
    var x: Int
    var y: Int

    static func + (lhs: Vector, rhs: Vector) -> Vector {
        return Vector(x: lhs.x [1] rhs.x, y: lhs.y + rhs.y)
    }
}
Drag options to blanks, or click blank then click option'
A*
B-
C+
D/
Attempts:
3 left
💡 Hint
Common Mistakes
Using - instead of + for addition.
Forgetting to make the function static.
Not returning a new Vector instance.
2fill in blank
medium

Complete the code to overload the == operator to compare two Vector instances.

Swift
struct Vector {
    var x: Int
    var y: Int

    static func == (lhs: Vector, rhs: Vector) -> Bool {
        return lhs.x [1] rhs.x && lhs.y == rhs.y
    }
}
Drag options to blanks, or click blank then click option'
A!=
B==
C>
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using != instead of ==.
Comparing only one coordinate.
Not returning a Bool value.
3fill in blank
hard

Fix the error in the operator overloading function to multiply a Vector by an integer scalar.

Swift
struct Vector {
    var x: Int
    var y: Int

    static func * (vector: Vector, scalar: Int) -> Vector {
        return Vector(x: vector.x [1] scalar, y: vector.y * scalar)
    }
}
Drag options to blanks, or click blank then click option'
A+
B-
C/
D*
Attempts:
3 left
💡 Hint
Common Mistakes
Using + or - instead of *.
Multiplying only one coordinate.
Returning the wrong type.
4fill in blank
hard

Fill both blanks to overload the - operator to subtract two Vector instances.

Swift
struct Vector {
    var x: Int
    var y: Int

    static func - (lhs: Vector, rhs: Vector) -> Vector {
        return Vector(x: lhs.x [1] rhs.x, y: lhs.y [2] rhs.y)
    }
}
Drag options to blanks, or click blank then click option'
A-
B+
C*
D/
Attempts:
3 left
💡 Hint
Common Mistakes
Using + instead of -.
Mixing operators between x and y.
Returning incorrect Vector values.
5fill in blank
hard

Fill all three blanks to overload the += operator for Vector addition and assignment.

Swift
struct Vector {
    var x: Int
    var y: Int

    static func += (lhs: inout Vector, rhs: Vector) {
        lhs.x [1]= rhs.x
        lhs.y [2]= rhs.y
    }

    static func + (lhs: Vector, rhs: Vector) -> Vector {
        return Vector(x: lhs.x [3] rhs.x, y: lhs.y + rhs.y)
    }
}
Drag options to blanks, or click blank then click option'
A+
B-
C*
D/
Attempts:
3 left
💡 Hint
Common Mistakes
Using -= or other operators instead of +=.
Forgetting to mark lhs as inout.
Mixing operators in the + function.