Challenge - 5 Problems
Swift Identity Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Swift code using identity operator?
Consider the following Swift code. What will be printed to the console?
Swift
class Person {} let personA = Person() let personB = personA let personC = Person() if personA === personB { print("Same instance") } else { print("Different instances") } if personA === personC { print("Same instance") } else { print("Different instances") }
Attempts:
2 left
💡 Hint
Remember that === checks if two variables point to the exact same object in memory.
✗ Incorrect
personB is assigned from personA, so both point to the same object. personC is a new instance, so it is different.
❓ Predict Output
intermediate1:30remaining
What does this code print when using !== operator?
Look at this Swift code. What will be the output?
Swift
class Box {} let box1 = Box() let box2 = Box() if box1 !== box2 { print("Boxes are not the same instance") } else { print("Boxes are the same instance") }
Attempts:
2 left
💡 Hint
!== means the two references do not point to the same object.
✗ Incorrect
box1 and box2 are two different instances, so !== returns true and prints the first message.
🧠 Conceptual
advanced1:00remaining
Which statement about === and !== in Swift is true?
Choose the correct statement about the identity operators === and !== in Swift.
Attempts:
2 left
💡 Hint
Think about what identity means in terms of objects and memory.
✗ Incorrect
=== and !== check if two references point to the same object instance, not just equal values.
❓ Predict Output
advanced2:30remaining
What is the output of this Swift code with optional references and identity check?
Analyze this Swift code and determine what it prints.
Swift
class Animal {} let animal1: Animal? = Animal() let animal2: Animal? = animal1 let animal3: Animal? = nil if animal1 === animal2 { print("animal1 and animal2 are identical") } else { print("animal1 and animal2 are not identical") } if animal1 !== animal3 { print("animal1 and animal3 are not identical") } else { print("animal1 and animal3 are identical") }
Attempts:
2 left
💡 Hint
Optional references can be compared with identity operators; nil is a special case.
✗ Incorrect
animal1 and animal2 point to the same instance, so === is true. animal3 is nil, so !== with animal1 is true.
🧠 Conceptual
expert1:30remaining
Why can't identity operators === and !== be used with Swift value types like structs?
Select the best explanation for why === and !== cannot be applied to structs or enums in Swift.
Attempts:
2 left
💡 Hint
Think about how value types behave differently from reference types.
✗ Incorrect
Value types like structs and enums are copied on assignment, so each variable has its own copy without shared identity.