0
0
Swiftprogramming~20 mins

Is operator for type checking in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Type Checker Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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")
}
ACompile-time error
BIt's not a dog
CIt's a dog
DRuntime error
Attempts:
2 left
💡 Hint
The 'is' operator checks if an instance is of a certain type or inherits from it.
Predict Output
intermediate
2: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")
}
AString detected
BNot a String
CCompile-time error
DRuntime error
Attempts:
2 left
💡 Hint
The 'is' operator checks if the value is of the specified type.
Predict Output
advanced
2: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")
}
AIt's a vehicle
BIt's not a vehicle
CCompile-time error
DRuntime error
Attempts:
2 left
💡 Hint
The 'is' operator works with protocol conformance as well as class inheritance.
Predict Output
advanced
2: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")
}
APrints "Not Optional Int"
BPrints "Optional Int"
CCompile-time error: 'is' cannot check optional type like this
DRuntime error: unexpected nil
Attempts:
2 left
💡 Hint
Check how 'is' works with optional types and non-optional values.
🧠 Conceptual
expert
2: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.
AThe 'is' operator performs a runtime cast and changes the instance type if the check passes.
BThe 'is' operator checks if an instance is exactly of the specified type, excluding subclasses or protocol conformances.
CThe 'is' operator can only be used with classes, not with structs or enums.
DThe 'is' operator checks if an instance is of the specified type or any subclass, including protocol conformance, returning true if so.
Attempts:
2 left
💡 Hint
Think about inheritance and protocol conformance in Swift type checking.