Recall & Review
beginner
What does the
is operator do in Swift?The
is operator checks if an instance is of a certain type or inherits from that type. It returns true if the instance matches the type, otherwise false.Click to reveal answer
beginner
How do you use the
is operator in an if statement?You write:
if object is SomeType { /* code */ }. This runs the code inside the block only if object is of type SomeType or a subclass.Click to reveal answer
intermediate
Can the
is operator check for protocol conformance?Yes! The <code>is</code> operator can check if an instance conforms to a protocol, not just class or struct types.Click to reveal answer
intermediate
What is the difference between
is and as? in Swift?is checks if an instance is of a type and returns a Boolean. as? tries to cast the instance to that type and returns an optional value.Click to reveal answer
beginner
Example: What does this code print?<br><pre>let value: Any = 5<br>if value is Int { print("It's an Int") }</pre>It prints:
It's an Int because the value 5 is an integer and the is operator confirms that.Click to reveal answer
What does the
is operator return when used in Swift?✗ Incorrect
The
is operator returns true or false depending on whether the instance is of the specified type.Which of these can the
is operator check for?✗ Incorrect
The
is operator can check if an instance conforms to a protocol.What will this code print?<br>
let text: Any = "Hello"<br>if text is String { print("It's a String") }✗ Incorrect
The variable
text holds a string, so text is String is true.What is the result of
value is Double if value is an Int?✗ Incorrect
An
Int is not a Double, so the check returns false.Which operator tries to convert an instance to a type and returns an optional?
✗ Incorrect
as? attempts to cast and returns an optional value.Explain how the
is operator works in Swift and give a simple example.Think about how you check if something is a certain kind of thing in real life.
You got /3 concepts.
Describe the difference between
is and as? operators in Swift.One checks type, the other tries to change type.
You got /3 concepts.