Bird
Raised Fist0
Swiftprogramming~20 mins

Opaque types with some keyword in Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Opaque Types Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of function returning opaque type
What is the output of this Swift code using some keyword for opaque return type?
Swift
protocol Shape {
    func area() -> Double
}

struct Circle: Shape {
    var radius: Double
    func area() -> Double {
        return Double.pi * radius * radius
    }
}

func makeCircle() -> some Shape {
    return Circle(radius: 3)
}

print(Int(makeCircle().area()))
A18
B9
C28
DRuntime error
Attempts:
2 left
💡 Hint
Recall the formula for the area of a circle and how opaque types hide the concrete type but preserve behavior.
❓ Predict Output
intermediate
2:00remaining
Opaque type with conditional return
What will be printed by this Swift code using some keyword with conditional return?
Swift
protocol Animal {
    func sound() -> String
}

struct Dog: Animal {
    func sound() -> String { "Woof" }
}

struct Cat: Animal {
    func sound() -> String { "Meow" }
}

func makePet(_ isDog: Bool) -> some Animal {
    if isDog {
        return Dog()
    } else {
        return Dog() // Note: returns Dog in both cases
    }
}

print(makePet(false).sound())
ARuntime error
BWoof
CCompile-time error
DMeow
Attempts:
2 left
💡 Hint
Remember that opaque types must always return the same concrete type, even if conditions differ.
🔧 Debug
advanced
2:00remaining
Identify the error with opaque type mismatch
What error does this Swift code produce and why?
Swift
protocol Vehicle {
    func wheels() -> Int
}

struct Bike: Vehicle {
    func wheels() -> Int { 2 }
}

struct Car: Vehicle {
    func wheels() -> Int { 4 }
}

func makeVehicle(_ useBike: Bool) -> some Vehicle {
    if useBike {
        return Bike()
    } else {
        return Car()
    }
}
ACompile-time error: Function with opaque return type must return same concrete type in all paths
BRuntime error: Cannot cast Bike to Car
CNo error, compiles and runs fine
DCompile-time error: Protocol Vehicle not conformed by Bike
Attempts:
2 left
💡 Hint
Opaque types require the same concrete type returned in every return path.
🧠 Conceptual
advanced
2:00remaining
Why use opaque types with some keyword?
Which of the following best explains the main advantage of using some keyword for opaque return types in Swift?
AIt disables type checking for the returned value
BIt forces the function to return only protocol types without any concrete implementation
CIt allows returning multiple different types from the same function dynamically
DIt hides the concrete return type while preserving type safety and allows the compiler to optimize code
Attempts:
2 left
💡 Hint
Think about abstraction and performance benefits.
❓ Predict Output
expert
3:00remaining
Output of nested opaque types with some keyword
What is the output of this Swift code using nested opaque types with some keyword?
Swift
protocol Container {
    associatedtype Item
    func getItem() -> Item
}

struct Box<T>: Container {
    var item: T
    func getItem() -> T { item }
}

func makeBox() -> some Container {
    Box(item: 42)
}

func wrapBox() -> some Container {
    makeBox()
}

print(wrapBox().getItem())
A42
BCompile-time error: Opaque type mismatch
COptional(42)
DRuntime error: Cannot convert Box<Int> to Container
Attempts:
2 left
💡 Hint
Opaque types can be nested if the concrete type is consistent.

Practice

(1/5)
1. What does the some keyword do when used in a Swift function's return type?
easy
A. It forces the function to return a specific concrete type.
B. It hides the exact return type but guarantees it conforms to a protocol.
C. It makes the function return any type without restrictions.
D. It allows the function to return multiple different types at runtime.

Solution

  1. Step 1: Understand the purpose of some keyword

    The some keyword in Swift is used to declare an opaque return type, which means the exact type is hidden but it must conform to a specified protocol.
  2. Step 2: Compare with other options

    The other options describe behaviors that do not match the opaque type concept: forcing a concrete type, returning any type freely, or allowing multiple types at runtime.
  3. Final Answer:

    It hides the exact return type but guarantees it conforms to a protocol. -> Option B
  4. Quick Check:

    Opaque types = hidden concrete type with protocol conformance [OK]
Hint: Remember: some hides type but keeps protocol rules [OK]
Common Mistakes:
  • Thinking some allows any return type without constraints
  • Confusing some with generics
  • Believing some returns multiple types dynamically
2. Which of the following is the correct syntax to declare a function returning an opaque type conforming to View protocol?
easy
A. func makeView() -> some View { Text("Hello") }
B. func makeView() -> any View { Text("Hello") }
C. func makeView() -> View { Text("Hello") }
D. func makeView() -> some View() { Text("Hello") }

Solution

  1. Step 1: Identify correct syntax for opaque return type

    The correct syntax uses some followed by the protocol name without parentheses: -> some View.
  2. Step 2: Check each option

    func makeView() -> some View { Text("Hello") } matches the correct syntax. func makeView() -> any View { Text("Hello") } uses any which is for existential types, not opaque. func makeView() -> View { Text("Hello") } returns the protocol type directly, which is not allowed. func makeView() -> some View() { Text("Hello") } incorrectly adds parentheses after View.
  3. Final Answer:

    func makeView() -> some View { Text("Hello") } -> Option A
  4. Quick Check:

    Opaque type syntax = -> some Protocol [OK]
Hint: Use some without parentheses for opaque types [OK]
Common Mistakes:
  • Using any instead of some for opaque types
  • Adding parentheses after protocol name
  • Returning protocol type directly instead of opaque type
3. What will be the output of this Swift code?
protocol Shape {
    func area() -> Double
}

struct Circle: Shape {
    var radius: Double
    func area() -> Double { 3.14 * radius * radius }
}

func makeShape() -> some Shape {
    Circle(radius: 2)
}

print(makeShape().area())
medium
A. 0.0
B. 4.0
C. 12.56
D. Error: Cannot use 'some' here

Solution

  1. Step 1: Understand the code flow

    The function makeShape() returns an opaque type conforming to Shape, specifically a Circle with radius 2.
  2. Step 2: Calculate the area

    The area of the circle is calculated as 3.14 * 2 * 2 = 12.56.
  3. Final Answer:

    12.56 -> Option C
  4. Quick Check:

    Circle area = π * r² = 12.56 [OK]
Hint: Calculate area using radius 2 and π=3.14 [OK]
Common Mistakes:
  • Confusing some with errors in return type
  • Using wrong formula for area
  • Assuming runtime error due to opaque type
4. Identify the error in this Swift code using opaque types:
protocol Animal {
    func sound() -> String
}

struct Dog: Animal {
    func sound() -> String { "Bark" }
}

struct Cat: Animal {
    func sound() -> String { "Meow" }
}

func makeAnimal(_ type: String) -> some Animal {
    if type == "dog" {
        return Dog()
    } else {
        return Cat()
    }
}
medium
A. Function returns different concrete types violating opaque type rules.
B. Missing protocol conformance in structs.
C. Incorrect function return type syntax.
D. No error; code is correct.

Solution

  1. Step 1: Understand opaque type restrictions

    Functions returning some Protocol must always return the same concrete type, even if hidden.
  2. Step 2: Analyze the function's return paths

    This function returns Dog or Cat depending on input, which breaks the opaque type rule.
  3. Final Answer:

    Function returns different concrete types violating opaque type rules. -> Option A
  4. Quick Check:

    Opaque type = single hidden type only [OK]
Hint: Opaque return must be one concrete type, not multiple [OK]
Common Mistakes:
  • Returning different types for opaque return
  • Confusing opaque types with protocol types
  • Ignoring compiler error about inconsistent return types
5. You want to write a function that returns an opaque type conforming to Collection protocol, but the collection should be filtered to only even numbers from an input array. Which of these implementations correctly uses some keyword and returns the filtered collection?
hard
A. func evenNumbers(from numbers: [Int]) -> some Collection { return numbers.sorted() }
B. func evenNumbers(from numbers: [Int]) -> some Collection { return numbers.map { $0 * 2 } }
C. func evenNumbers(from numbers: [Int]) -> [Int] { numbers.filter { $0 % 2 == 0 } }
D. func evenNumbers(from numbers: [Int]) -> some Collection { numbers.filter { $0 % 2 == 0 } }

Solution

  1. Step 1: Understand the requirement

    The function must return an opaque type conforming to Collection that contains only even numbers filtered from the input.
  2. Step 2: Evaluate each option

    func evenNumbers(from numbers: [Int]) -> some Collection { numbers.filter { $0 % 2 == 0 } } returns the filtered array using filter, which is a Collection and matches the requirement with some Collection. func evenNumbers(from numbers: [Int]) -> some Collection { return numbers.map { $0 * 2 } } returns doubled numbers, not filtered evens. func evenNumbers(from numbers: [Int]) -> [Int] { numbers.filter { $0 % 2 == 0 } } returns a concrete array type, not opaque. func evenNumbers(from numbers: [Int]) -> some Collection { return numbers.sorted() } returns sorted numbers but not filtered evens.
  3. Final Answer:

    func evenNumbers(from numbers: [Int]) -> some Collection { numbers.filter { $0 % 2 == 0 } } -> Option D
  4. Quick Check:

    Filter evens + opaque return = func evenNumbers(from numbers: [Int]) -> some Collection { numbers.filter { $0 % 2 == 0 } } [OK]
Hint: Use filter and some Collection for opaque filtered result [OK]
Common Mistakes:
  • Returning wrong filtered or mapped collection
  • Returning concrete type instead of opaque
  • Not filtering for even numbers
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