Daily iOS
Swift

Generics vs Any

During code review you find the same logic overloaded per type: func larger(_ a: Int, _ b: Int) -> Int, larger(_ a: Double, _ b: Double) -> Double, larger(_ a: String, ...). You want to propose one generic function instead. How is taking a generic parameter different from taking Any?

How would an interviewer hear this answer? You'll see whether they'd move on, dig in, or say no, and which sentences would trip you up. Your score doesn't change.
See the short answer

A generic puts a constraint like Comparable on the placeholder T, removing the duplication while keeping compile-time type checking. Any needs casts and fails at runtime.

Share a question