SwiftQuiz
#15

Constrained Extension and Generic Context

  • conditional-conformance
  • generics
  • dispatch
Swift 6.3.2 Report an issue

Verified quizzes have their expected answer checked by compiling and running the code with the listed Swift toolchain during the site build.

struct Box<T> {}
extension Box where T == Int {
    func tag() -> String {
        "int"
    }
}

extension Box {
    func tag() -> String {
        "any"
    }
}

print(Box<Int>().tag())
print(Box<String>().tag())

func describe<T>(_ b: Box<T>) {
    print(b.tag())
}

describe(Box<Int>())
Hint

Look at the third call carefully. The runtime type of b inside describe is Box<Int>. So why doesn't the constrained extension apply?

Your answer

What does this program do?