0
0
Swiftprogramming~5 mins

Is operator for type checking in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AThe memory address of the instance
BThe instance cast to the specified type
CThe size of the instance in bytes
DA Boolean indicating if the instance matches the type
Which of these can the is operator check for?
AProtocol conformance
BClass type only
CVariable value
DFunction return type
What will this code print?<br>
let text: Any = "Hello"<br>if text is String { print("It's a String") }
AError
BNothing
CIt's a String
DIt's an Int
What is the result of value is Double if value is an Int?
Atrue
Bfalse
CRuntime error
DOptional Double
Which operator tries to convert an instance to a type and returns an optional?
Aas?
Bis
C==
D!=
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.