Challenge - 5 Problems
Swift Type Checker 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 'is' operator?
Consider the following Swift code. What will be printed when it runs?
Swift
class Animal {} class Dog: Animal {} let pet: Animal = Dog() if pet is Dog { print("It's a dog") } else { print("It's not a dog") }
Attempts:
2 left
💡 Hint
The 'is' operator checks if an instance is of a certain type or inherits from it.
✗ Incorrect
The variable 'pet' is declared as type Animal but holds an instance of Dog. The 'is' operator returns true if the instance is of the specified type or a subclass. So 'pet is Dog' is true, printing "It's a dog".
❓ Predict Output
intermediate2:00remaining
What does this Swift code print when checking type with 'is'?
Analyze the code below and select the output:
Swift
let value: Any = 42 if value is String { print("String detected") } else { print("Not a String") }
Attempts:
2 left
💡 Hint
The 'is' operator checks if the value is of the specified type.
✗ Incorrect
The variable 'value' holds an Int (42), not a String. So 'value is String' is false, printing "Not a String".
❓ Predict Output
advanced2:00remaining
What is the output of this Swift code using 'is' with protocol conformance?
Given the code below, what will be printed?
Swift
protocol Vehicle {} class Car: Vehicle {} class Bicycle {} let myRide: Any = Car() if myRide is Vehicle { print("It's a vehicle") } else { print("It's not a vehicle") }
Attempts:
2 left
💡 Hint
The 'is' operator works with protocol conformance as well as class inheritance.
✗ Incorrect
The instance is of class Car which conforms to Vehicle protocol. So 'myRide is Vehicle' is true, printing "It's a vehicle".
❓ Predict Output
advanced2:00remaining
What error does this Swift code raise when using 'is' incorrectly?
Examine the code and select the error it produces when compiled or run:
Swift
let number = 10 if number is Int? { print("Optional Int") } else { print("Not Optional Int") }
Attempts:
2 left
💡 Hint
Check how 'is' works with optional types and non-optional values.
✗ Incorrect
The variable 'number' is Int, not Int?. The 'is' operator returns false because 'number' is not an Optional Int, so it prints "Not Optional Int". No error occurs.
🧠 Conceptual
expert2:00remaining
Which option correctly explains the behavior of 'is' operator in Swift?
Select the statement that best describes how the 'is' operator works in Swift.
Attempts:
2 left
💡 Hint
Think about inheritance and protocol conformance in Swift type checking.
✗ Incorrect
The 'is' operator returns true if the instance is of the specified type or any subclass, or if it conforms to a protocol. It does not change the instance type and works with classes, structs, enums, and protocols.