Bird
Raised Fist0
Swiftprogramming~20 mins

Existential types (any keyword) in Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Existential Types Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of existential type usage with 'any' keyword
What is the output of this Swift code using the 'any' keyword for existential types?
Swift
protocol Greetable {
    func greet() -> String
}

struct Person: Greetable {
    func greet() -> String {
        "Hello from Person"
    }
}

func welcome(_ greeter: any Greetable) {
    print(greeter.greet())
}

let p = Person()
welcome(p)
AProtocol 'Greetable' cannot be used as a type
BError: Missing 'any' keyword before 'Greetable'
CHello from Person
DHello from any
Attempts:
2 left
💡 Hint
Remember that 'any' keyword is used to explicitly mark existential types in Swift 5.7+.
❓ Predict Output
intermediate
2:00remaining
Value stored in variable with 'any' existential type
What is the value of variable 'message' after running this Swift code?
Swift
protocol Describable {
    func describe() -> String
}

struct Animal: Describable {
    func describe() -> String {
        "I am an animal"
    }
}

let creature: any Describable = Animal()
let message = creature.describe()
A"I am a creature"
B"I am an animal"
CCompile-time error: protocol used without 'any'
DRuntime error: cannot call describe() on existential
Attempts:
2 left
💡 Hint
The 'any' keyword allows calling protocol methods on the existential value.
🔧 Debug
advanced
2:00remaining
Identify the error with existential type usage
What error does this Swift code produce?
Swift
protocol Runnable {
    func run()
}

func execute(task: Runnable) {
    task.run()
}

struct Job: Runnable {
    func run() {
        print("Job running")
    }
}

let job = Job()
execute(task: job)
ANo error, prints 'Job running'
BError: Missing 'any' keyword before 'Runnable'
CError: Protocol 'Runnable' can only be used as a generic constraint because it has Self or associated type requirements
DRuntime error: cannot call run() on protocol type
Attempts:
2 left
💡 Hint
Check if the protocol has associated types or Self requirements.
❓ Predict Output
advanced
2:00remaining
Output when using 'any' with protocol with associated type
What happens when you try to compile and run this Swift code?
Swift
protocol Container {
    associatedtype Item
    func getItem() -> Item
}

struct Box: Container {
    func getItem() -> Int {
        42
    }
}

func printItem(container: any Container) {
    print(container.getItem())
}

let box = Box()
printItem(container: box)
ACompile-time error: Missing 'any' keyword before 'Container'
BPrints 42
CRuntime error: cannot call getItem() on existential
DCompile-time error: Protocol 'Container' can only be used as a generic constraint because it has Self or associated type requirements
Attempts:
2 left
💡 Hint
Protocols with associated types cannot be used as existential types directly.
🧠 Conceptual
expert
2:00remaining
Why use 'any' keyword for existential types in Swift?
Which of the following best explains the purpose of the 'any' keyword in Swift existential types?
AIt explicitly marks a protocol type as an existential to improve code clarity and future-proofing
BIt enables protocols with associated types to be used as types directly
CIt automatically converts protocol types into generic types
DIt disables protocol conformance checking at compile time
Attempts:
2 left
💡 Hint
Think about why Swift introduced the 'any' keyword in version 5.7.

Practice

(1/5)
1. What does the any keyword indicate in Swift when used with a protocol type?
easy
A. It creates a new protocol that inherits from the original.
B. It marks the type as existential, allowing any value conforming to the protocol.
C. It restricts the type to only one specific conforming type.
D. It converts the protocol into a concrete class.

Solution

  1. Step 1: Understand the role of any in Swift

    The any keyword is used to mark a type as existential, meaning it can hold any value that conforms to a given protocol.
  2. Step 2: Compare with other options

    The incorrect options describe behaviors unrelated to any. It does not create new protocols, restrict to one type, or convert protocols to classes.
  3. Final Answer:

    It marks the type as existential, allowing any value conforming to the protocol. -> Option B
  4. Quick Check:

    any means existential type [OK]
Hint: Remember: any means 'any conforming type' [OK]
Common Mistakes:
  • Thinking any creates a new protocol
  • Confusing any with type restriction
  • Assuming any converts protocols to classes
2. Which of the following is the correct syntax to declare a variable that can hold any value conforming to the protocol Drawable using existential types?
easy
A. var shape: Drawable
B. var shape: Drawable & any
C. var shape: any Drawable
D. var shape: Drawable<any>

Solution

  1. Step 1: Recall the syntax for existential types

    In Swift, to declare a variable that can hold any value conforming to a protocol, you use any ProtocolName. So here, it is any Drawable.
  2. Step 2: Analyze each option

    var shape: Drawable misses any, so it is not explicit existential. var shape: Drawable & any and var shape: Drawable<any> have incorrect syntax. Only var shape: any Drawable uses the correct syntax.
  3. Final Answer:

    var shape: any Drawable -> Option C
  4. Quick Check:

    Existential syntax = any Protocol [OK]
Hint: Use any before protocol name for existential types [OK]
Common Mistakes:
  • Omitting any keyword
  • Placing any after protocol name
  • Using angle brackets incorrectly
3. What will be the output of the following Swift code?
protocol Greetable {
    func greet() -> String
}

struct Person: Greetable {
    func greet() -> String { "Hello" }
}

let greeter: any Greetable = Person()
print(greeter.greet())
medium
A. Hello
B. Error: Protocol method not implemented
C. Runtime error
D. nil

Solution

  1. Step 1: Understand the protocol and struct

    The protocol Greetable requires a greet() method returning a String. The struct Person implements this method returning "Hello".
  2. Step 2: Analyze the existential usage and output

    The variable greeter is declared as any Greetable and assigned a Person instance. Calling greeter.greet() calls the implemented method and returns "Hello".
  3. Final Answer:

    Hello -> Option A
  4. Quick Check:

    Existential calls implemented method = "Hello" [OK]
Hint: Existential calls protocol methods on conforming instance [OK]
Common Mistakes:
  • Expecting a compile or runtime error
  • Thinking protocol methods are not accessible
  • Assuming nil is returned
4. Identify the error in the following Swift code using existential types and fix it:
protocol Runnable {
    func run()
}

struct Dog: Runnable {
    func run() { print("Dog runs") }
}

var runner: Runnable = Dog()
runner.run()
medium
A. Missing any keyword before Runnable in variable declaration.
B. Dog does not conform to Runnable protocol.
C. run() method should return a value.
D. Variable runner should be a constant (let) instead of var.

Solution

  1. Step 1: Check variable declaration syntax

    Since Swift 5.7, existential types require the any keyword explicitly. The declaration var runner: Runnable is invalid; it should be var runner: any Runnable.
  2. Step 2: Verify other parts

    Dog conforms correctly, run() returns Void (allowed), and var is allowed. So only missing any is the error.
  3. Final Answer:

    Missing any keyword before Runnable in variable declaration. -> Option A
  4. Quick Check:

    Existential types need any keyword [OK]
Hint: Add any before protocol for existential variables [OK]
Common Mistakes:
  • Omitting any keyword
  • Thinking protocol conformance is missing
  • Expecting run() to return a value
5. You want to write a function that accepts any value conforming to the Codable protocol and returns its JSON string representation. Which is the correct way to declare the function parameter using existential types?
hard
A. func encodeToJSON(value: Codable & any) -> String
B. func encodeToJSON(value: Codable) -> String
C. func encodeToJSON(value: T) -> String
D. func encodeToJSON(value: any Codable) -> String

Solution

  1. Step 1: Understand existential vs generic parameters

    Using any Codable declares an existential type parameter that can accept any value conforming to Codable. This matches the question requirement.
  2. Step 2: Analyze each option

    func encodeToJSON(value: Codable) -> String omits any, which is invalid syntax for existential types. func encodeToJSON(value: T) -> String uses generics, which is valid but not existential. func encodeToJSON(value: Codable & any) -> String has incorrect syntax. func encodeToJSON(value: any Codable) -> String is correct.
  3. Final Answer:

    func encodeToJSON(value: any Codable) -> String -> Option D
  4. Quick Check:

    Existential parameter syntax = any Protocol [OK]
Hint: Use any before protocol for existential function parameters [OK]
Common Mistakes:
  • Using generics instead of existential types
  • Omitting any keyword
  • Incorrect syntax with & or angle brackets
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard